当我从服务器下载大约 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/