首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >优化文件下载

优化文件下载
EN

Stack Overflow用户
提问于 2014-04-07 18:43:25
回答 2查看 251关注 0票数 0

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

代码语言:javascript
复制
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份报告中,它大约有25 and,而我有一个高速互联网连接。我对通过java下载文件相当陌生,需要一些帮助。我总共叫这个方法129次。

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

提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-07 18:47:35

瓶颈在这里:

代码语言:javascript
复制
int i = 0;
while ((i = bis.read()) != -1) {
    bos.write(i);
}

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

代码语言:javascript
复制
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#copyApache Commons IO,它已经为您做到了这一点:

代码语言:javascript
复制
IOUtils.copy(bis, bos);
票数 3
EN

Stack Overflow用户

发布于 2014-04-07 18:55:16

如果您正在使用Java 7,这是非常容易的。当您想要写入文件时,请执行以下操作:

代码语言:javascript
复制
final Path dstFile = Paths.get("C:/users/filename");

if (responseCode == 200) {
    try (
        final InputStream in = con.getInputStream();
    ) {
        Files.copy(in, dstFile, StandardOpenOption.CREATE_NEW);
    }
} // etc
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22920498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档