简体   繁体   English

在URL中有效地将文件从URL读入byte []

[英]Efficiently read file from URL into byte[] in Java

I'm trying to find a more efficient method of reading a file from a remote URL and saving it into a byte array. 我正在尝试找到一种更有效的方法从远程URL读取文件并将其保存到字节数组中。 Here is what I currently have: 这是我目前拥有的:

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;
}

As you can see, I currently pass the URL into the method, where it uses an InputStream object to read in the bytes of the file. 如您所见,我目前将URL传递给方法,在该方法中,它使用InputStream对象读取文件的字节。 This method uses Apache Commons IOUtils. 此方法使用Apache Commons IOUtils。 However, this method call tends to take a relatively long time to run. 但是,此方法调用往往需要相对较长的时间才能运行。 When retrieving hundreds, thousands, or hundreds of thousands of files one right after another, it gets quite slow. 当一个接一个地检索数百,数千或数十万个文件时,它变得非常慢。 Is there a way I could improve this method so that it runs more efficiently? 有没有办法可以改进这种方法,使其更有效地运行? I have considered multithreading but I would like to save that as a last resort. 我考虑过多线程,但我想保留它作为最后的手段。

Your way of doing it seems like absolutely ok. 你这样做的方式似乎绝对可以。

But if you saying: 但如果你说:

"However, this method call tends to take a relatively long time to run" “但是,这种方法调用往往需要相对较长的时间来运行”

You can have follow problems : 你可以有以下问题:

  • Network, connection issue 网络,连接问题

  • Are you sure that download each file in separate thread? 您确定在单独的线程中下载每个文件吗?

If you are using multithreading for that, be sure that VM args -XmsYYYYM and -XmxYYYYM configured well, because if not you can face problem , that your processor not using all cores. 如果您正在使用多线程,请确保VM args -XmsYYYYM-XmxYYYYM配置良好,因为如果不是您可能遇到问题,那么您的处理器不使用所有内核。 I have faced this problem some time ago. 我前段时间遇到过这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM