使用Java优化下载速度

时间:2013-03-19 11:29:20

标签: java performance download fileinputstream

我在java中有一个从web下载文件的方法,但是通过java代码下载比使用任何浏览器下载时慢。

我的代码如下,

 public void downloadFile(String downloadURL) {


            System.out.println("Starting file download .....");


            BufferedInputStream in = null;
            FileOutputStream fout = null;
            try {
                URL u = new URL(downloadURL);
                HttpURLConnection uc = (HttpURLConnection) u.openConnection();
                String fileName = uc.getHeaderField("Content-Disposition");
                fileName = YouTubeDownloader.parseResponse(fileName, "filename=\"", "\"");
                System.out.println(fileName);

                if (uc.getHeaderField("Content-Length") == null) {
                    System.out.println("File Length zero!!!!");

                }




                float fileSize = Float.parseFloat(uc.getHeaderField("Content-Length"));

                in = new BufferedInputStream(uc.getInputStream());

                System.out.println("File size : " + fileSize);


                fout = new FileOutputStream("c:\\Dinesh\\" + fileName);

                byte data[] = new byte[1024];
                int count = 0;
                int downloaded = 0;
                while ((count = in.read(data, 0, 1024)) != -1) {

                    downloaded += count;
                    int downloadPercentage = (int) ((downloaded / fileSize) * 100);
                    System.out.println(downloadPercentage);
                    fout.write(data, 0, count);
                }

                System.out.println("File download completed.....");

            } catch (Exception e) {
                System.out.println(e);
            }
    }

由于缓冲区较小,下载速度是否太慢?

我可以增加缓冲区大小或如何优化缓冲区大小以降低下载速度吗?

我需要修改哪些内容?

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您不需要监控进度,请尝试以下操作:

Path saveFile = Paths.get("C:\\Dinesh", fileName);
Files.copy(uc.getInputStream(), saveFile);