java - 优化文件下载

标签 java http get

当我从服务器下载大约 129 个报告时,我正在尝试优化我的代码。所有报告都有不同的 URL,这是我开发的代码:

public static void getReport(String eqID, String reportCode, String reportName, String fileName) throws IOException{

        String url = "http://example.com/api?function=getData&eqId=" + eqID;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        Authenticator.setDefault (new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication ("username", "password".toCharArray());
            }
        });

        // optional default is GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();

        if(responseCode == 200){
            System.out.println("Downloading: " + reportName);
            File file = new File("C:/Users/fileName);

            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getPath()));

            int i = 0;
            while ((i = bis.read()) != -1) {
                bos.write(i);
            }

            bos.flush();
            bis.close();
            bos.close();
        }
        else if(responseCode == 204){
            System.out.println("\nSending 'GET' request to: " + reportName);
            System.out.println("Response: Successful but report is empty. It will be skipped");
        }
    }

问题是处理这些下载需要花费太多时间。所有 129 份报告的大小约为 25MB,而且我有高速互联网连接。我对通过 java 下载文件还很陌生,需要一些帮助。我总共调用这个方法 129 次。

如果您可以推荐优化它的方法,或者只在 HTTP 连接上使用,而不是单独打开 129。

提前致谢!

最佳答案

瓶颈在这里:

int i = 0;
while ((i = bis.read()) != -1) {
    bos.write(i);
}

您正在逐字节读取,这在较大的文件中可能会花费大量时间。相反,按 block 读取文件,通常为 4KB 或 8KB:

int FILE_CHUNK_SIZE = 1024 * 4; //to make it easier to change to 8 KBs
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = input.read(chunk)) != -1) {
    bos.write(chunk, 0, bytesRead);
}
<小时/>

另一种选择是使用 IOUtils#copy来自Apache Commons IO它已经为你做到了这一点:

IOUtils.copy(bis, bos);

关于java - 优化文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22920498/

相关文章:

java - 我不断收到“无法找到符号方法compareTo”错误

svn - 如何阻止 1.6 版本以下的客户端访问 Subversion 服务器

xml - 事实上,API XML 在多次请求后被阻止

php - $_GET 复选框值在搜索结果中的 $_POST 之后未更新?

java - 如何确保我在 intelliJ 中应用了正确的代码格式

java - View.onClickListener - 如何获取 View 属性

java - JDBC未连接到Web服务中的数据库

http - 如何禁用内容长度检查?

javascript - 加载页面时多次获取请求

java - 如何使用 Rest Get Annotation for application/x-octet-stream Accept header