Java 实例 - 获取远程文件大小


以下实例演示了如何获取远程文件的大小:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8.  
  9. public class Main {
  10. public static void main(String[] argv)
  11. throws Exception {
  12. int size;
  13. URL url = new URL("http://www.shouce.ren/wp-content/themes/shouce.ren/assets/img/newlogo.png");
  14. URLConnection conn = url.openConnection();
  15. size = conn.getContentLength();
  16. if (size < 0)
  17. System.out.println("无法获取文件大小。");
  18. else
  19. System.out.println("文件大小为:" +
  20. + size + " bytes");
  21. conn.getInputStream().close();
  22. }
  23. }

以上代码运行输出结果为:

  1. 文件大小为:4261 bytes