如何使用 Java 从服务器获取文件大小
问题描述
如何从服务器获取文件大小?
解决方案
以下示例演示了如何从服务器获取文件大小。
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] argv) throws Exception {
int size;
URL url = new URL("http://www.server.com");
URLConnection conn = url.openConnection();
size = conn.getContentLength();
if (size < 0) System.out.println("Could not determine file size.");
else System.out.println("The size of file is = " + size + "bytes");
conn.getInputStream().close();
}
}
结果
上述代码示例将产生以下结果。
The size of file is = 1312bytes
以下是另一个从服务器获取文件大小的示例。
import java.net.URL;
import java.net.URLConnection;
public class NewClass {
public static void main(String[] argv) throws Exception {
int size;
URL url = new URL("https://www.tutorialspoint.com/javaexamples/net_multisoc.html");
URLConnection conn = url.openConnection();
size = conn.getContentLength();
if (size < 0) System.out.println("file size is empty.");
else System.out.println("File size is = " + size + "bytes");
conn.getInputStream().close();
}
}
上述代码示例将产生以下结果。
File size is = 18862bytes
java_networking.html

