我想从 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/