Java Examples - Getting the Size of a Remote File
The following example demonstrates how to get the size of a remote file:
Main.java File
import
java
.
net
.
URL
;
import
java
.
net
.
URLConnection
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
int
size
;
URL
url
=
new
URL
(
"
http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png
"
)
;
URLConnection
conn
=
url
.
openConnection
(
)
;
size
=
conn
.
getContentLength
(
)
;
if
(
size
<
0
)
System.
out
.
println
(
"
Unable to get the file size.
"
)
;
else
System
.
out
.
println
(
"
The file size is:
"
size
"
bytes
"
)
;
conn
.
getInputStream
(
)
.
close
(
)
;
}
}
The output of the above code is:
文件大小为:4261 bytes
Java Examples