如何从服务器获取文件大小

如何从服务器获取文件大小

在Java编程中,如何从服务器获取文件大小?

以下示例演示如何从服务器获取文件大小。

package com.yiibai;

import java.net.URL;
import java.net.URLConnection; public class GettingFileSize {
public static void main(String[] argv) throws Exception {
int size;
URL url = new URL("http://www.yiibai.com/downloads/host.txt");
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();
}
}
Java

上述代码示例将产生以下结果 -

The size of file is = 180822 bytes
Shell

示例-2

以下是如何从服务器获取文件大小的另一个示例。

package com.yiibai;

import java.net.URL;
import java.net.URLConnection; public class GettingFileSize2 {
public static void main(String[] argv) throws Exception {
int size;
URL url = new URL("http://www.yiibai.com/downloads/yiibaidb.zip");
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();
}
}
Java

上述代码示例将产生以下结果 -

File size is = 60098 bytes
05-11 16:25