2

我想从 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最简单的是什么......

4

1 回答 1

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();
于 2013-05-12T22:33:25.283 回答