【问题标题】:Stream file from URL to File without storing it in the memory将文件从 URL 流式传输到文件而不将其存储在内存中
【发布时间】:2013-05-12 22:29:47
【问题描述】:

我想从 URL 下载文件并将其存储到文件系统中。但是我有内存限制,我不想以前将它存储在内存中。我不是 java 专家,我对所有类 InputStream、BufferedReader、FileOutputStream 等感到有点迷茫。你能帮帮我吗?

现在我有:

URLConnection ucon = url.openConnection();
ucon.connect();
InputStream is = ucon.getInputStream();
// Create a reader for the input stream.
BufferedReader br = new BufferedReader(isr);

// ?

FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
// Here the content can be too big for the memory...
fos.write(content.getBytes());
fos.close();

拜托,你能给我一些线索吗?我也在考虑逐块阅读它,但我不确定使用 java 最简单的是什么......

【问题讨论】:

  • " I am a java expert and I am a bit lost with all the class InputStream, BufferedReader, FileOutputStream..." -- 您的意思是说您不是 Java 专家吗?因为这句话的两部分放在一起没有意义。
  • 太好了,谢谢。这更有意义。你有什么样的“内存限制”,为什么?您当前的代码如何不起作用?
  • 我在安卓上,我在想这些设备一定有内存限制。
  • 我仍然不明白为什么您认为使用 BufferedReader(您可以顺便设置其缓冲区大小)会占用太多内存。你应该没有限制使用它。
  • 我使用了 Sergi0 提出的方法,效果很好(这就是我说“逐块”时的想法)。抱歉没有说清楚。

标签: java android stream


【解决方案1】:

你可以使用apache commons

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

我猜它可能不适用于android 我用这个代码

InputStream input = connection.getInputStream();
byte[] buffer = new byte[4096];
int cnt = - 1;

OutputStream output = new FileOutputStream(file);
while ( (cnt = input.read(buffer)) != -1)
{
  output.write(buffer, 0, cnt);
}
output.close();

【讨论】:

  • 这个库在android平台上可用吗?如果没有,是否建议包含这个库?
  • 通常最好使用带有 connectionTimeout 和 readTimeout 参数的方法版本 - 否则,在某些情况下,您可能会发现阻塞时间过长。
猜你喜欢
  • 2015-07-13
  • 1970-01-01
  • 2019-10-14
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2015-07-27
相关资源
最近更新 更多