2

我正在尝试通过 http 连接下载二进制文件。但是,我的代码会引发 java.io.FileOutputStream.write(Unknown Source) 错误。我不确定我做错了什么。

public void GetFileDownload(String URI) throws IOException{ 
    /*
     * Given a URI this method will grab the binary data from that page over the http protocol
     */
    URL inputURI;
    HttpURLConnection connect;
    BufferedReader input;
        inputURI = new URL(URI);
        connect = (HttpURLConnection) inputURI.openConnection();
        connect.setReadTimeout(10000);
        connect.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401");
        connect.setRequestMethod("GET");
        input = new BufferedReader(new InputStreamReader(connect.getInputStream()));
        byte[] buffer = new byte[4096];
        int n = - 1;

        String file = "test";
        int i = 0;
        OutputStream output = new FileOutputStream(file);
        while (i != buffer.length - 1){
            i++;
            System.out.print(buffer[i]);
        }
        while ((n = input.read()) != -1)
            output.write(buffer, 0, n);
        output.close();
}
4

3 回答 3

1
     String link = "<YOUR_URL>/" + "download.jar"; // jar is binary 
      String            fileName = "download.jar";
      URL               url  = new URL( link );
      HttpURLConnection http = (HttpURLConnection)url.openConnection();
      InputStream  input  = http.getInputStream();
      byte[]       buffer = new byte[2048];
      int          n      = -1;
      OutputStream output = new FileOutputStream( new File( fileName ));
      while ((n = input.read(buffer)) != -1) { //make sure your to check -1 and target buffer to read from
         output.write( buffer, 0, n );
      }
      output.close();

上面的代码抛出 IOException 所以你需要处理异常。

于 2013-05-28T02:41:04.620 回答
1

你的复制循环是错误的。它应该是:

while ((n = input.read(buffer)) > 0)
{
    output.write(buffer, 0, n);
}

您正在导致数组索引超出范围条件。

于 2013-05-30T23:21:45.183 回答
0

而 ((n = input.read(buffer)) != -1)

您需要将目标缓冲区提供给 read 方法。

于 2013-05-28T02:40:57.220 回答