当从服务器下载大约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份报告中,它大约有25 and,而我有一个高速互联网连接。我对通过java下载文件相当陌生,需要一些帮助。我总共叫这个方法129次。
如果您可以推荐优化它的方法,或者只在HTTP连接上使用,而不是单独打开129。
提前感谢!
发布于 2014-04-07 18:47:35
瓶颈在这里:
int i = 0;
while ((i = bis.read()) != -1) {
bos.write(i);
}您正在逐字节读取,这会在较大的文件中花费大量时间。相反,按块读取文件,通常是在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);发布于 2014-04-07 18:55:16
如果您正在使用Java 7,这是非常容易的。当您想要写入文件时,请执行以下操作:
final Path dstFile = Paths.get("C:/users/filename");
if (responseCode == 200) {
try (
final InputStream in = con.getInputStream();
) {
Files.copy(in, dstFile, StandardOpenOption.CREATE_NEW);
}
} // etchttps://stackoverflow.com/questions/22920498
复制相似问题