java - 将文件从 URL 流式传输到文件而不将其存储在内存中

标签 java android stream

我想从 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();

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

最佳答案

你可以使用apache commons

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

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

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();

关于java - 将文件从 URL 流式传输到文件而不将其存储在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16512690/

相关文章:

java - 处理异常的构造函数

java - AmazonS3分段上传

android - 如何在 Kotlin 中完全实现 Navigation Drawer 模板

控制台应用程序中的 Java KeyListener

java - ExtJs 3组合框设置默认值

Android 布局图像

android - 设置警报对话框之间的时间

javascript - 获取流的内容长度

javascript - 我认为我没有正确有效地实现和使用可读流?

node.js - gulp.js - 如何将多个流返回到主流?