我正在尝试寻找一种更高效的方法,从远程URL读取文件并将其保存到字节数组中。以下是我目前拥有的代码:
private byte[] fetchRemoteFile(String location) throws Exception {
URL url = new URL(location);
InputStream is = null;
byte[] bytes = null;
try {
is = url.openStream ();
bytes = IOUtils.toByteArray(is);
} catch (IOException e) {
//handle errors
}
finally {
if (is != null) is.close();
}
return bytes;
}
正如你所看到的,我目前将URL传递给这个方法,在那里它使用InputStream对象读取文件的字节。该方法使用Apache Commons IOUtils。然而,这种方法调用往往需要相对较长的时间来运行。当一个接一个地检索数百、数千或数十万个文件时,它会变得非常缓慢。有没有办法可以改进这个方法,使其运行更高效?我考虑过多线程,但我希望把它作为最后的手段存下来。