读取URL内容的文件大小?

时间:2018-10-24 08:16:30

标签: java url size filesize

我正在尝试读取网络位置上的文件大小。

我可以通过请求http标头来阅读它。但是我首先使用InpuStream或BufferedInputStream的方法available()。虽然使用bis.read()读取字节,但使用available()则显示0。

为什么它不能与available()一起使用?

   public class GetNetworkLocation {
    public void main(String[] arg) {
     new GetNetworkLocation.startApp();
    }
    private void startApp() {
     getNetworkFile();
    }
    private void getNetworkFile() throws MalformedURLException, IOException, InterruptedException {
     try   {
     input = new URL(UrlString).openStream();
     bis = new BufferedInputStream(input);
     // Strange the content is 0 ?
     System.out.println("File size with BufferedInputStream" + " " + bis.available());
     System.out.println("File size with Http Head Request" + " " + bis.available());
     }
    } catch (MalformedURLException me) {System.out.println("Type a correct Network Address for your File!");}
   }
   public long getFileSize(new URL(UrlString)) {
    HttpURLConnection conn = null;
    try {
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("HEAD");
    return conn.getContentLengthLong();
   } catch (IOException e) {
   throw new RuntimeException(e);
  } finally {
  if (conn != null) {
   conn.disconnect();
  }
 }
}}   

0 个答案:

没有答案