如何使用java从URL下载.zip文件

时间:2014-12-24 20:12:37

标签: java

家伙! 我有个问题!我正在尝试使用以下代码从Internet下载.zip(大小为150 MB)文件:

public void downloadBuild(String srcURL, String destPath, int bufferSize, JTextArea debugConsole) throws FileNotFoundException, IOException {
    debugConsole.append(String.format("**********Start process downloading file. URL: %s**********\n", srcURL));
    try {
        URL url = new URL(srcURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("POST");
        httpConn.connect();
        in = httpConn.getInputStream();
        out = new FileOutputStream(destPath);
        byte buffer[] = new byte[bufferSize];
        int c = 0;
        while ((c = in.read(buffer)) > 0) {
            out.write(buffer, 0, c);
        }
        out.flush();
        debugConsole.append(String.format("**********File. has been dowloaded: Save path is: %s********** \n", destPath));
    } catch (IOException e) {
        debugConsole.append(String.format("**********Error! File was not downloaded. Detail: %s********** \n", e.toString()));
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
        }
    }
}

但文件未完全下载。 (只有4000字节)。我究竟做错了什么?

1 个答案:

答案 0 :(得分:1)

FileOutputStream("example.zip").getChannel().transferFrom(Channels.newChannel(new URL("http://www.example.com/example.zip").openStream()), 0, Long.MAX_VALUE);

简单的单行。有关详细信息,请阅读here