我想从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最简单的是什么......
答案 0 :(得分: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();