【发布时间】:2014-12-14 07:12:22
【问题描述】:
最近,当我试图在我的 android 应用程序中实现一个基本的文件下载器时,我在使用 InputStreams 和 OutputStreams 时遇到了麻烦。详细说明我就是这样做的。
我使用 apache HttpClient 类得到一个 InputStream 对象,然后尝试将流写入文件.. 但奇怪的是,当我缓冲 InputStream 或 OutputStream 时,我得到一个不可读的文件.. 这是代码..
//为了使代码简洁,我删除了异常并关闭了流..
private void download(InputStream in,String fileName){
//if i dont use the buffered thing and read directly from in everything is ok
// same is the buffered out i had to use in/outstream
BufferedInputStream bufferedIn = new BufferedInputStream(in);
FileOutputStream fout = new FileOutputStream(new File(fileName));
BufferedOutputstream bufferedOut = new BufferedOutputstream(fout);
int read = -1;
while((read = bufferedIn.read()) != -1){
bufferedOut.write(read);
}
//close the buffers
}
【问题讨论】:
-
不可读是什么意思?真的不可读吗?截断结果?空的文件 ?请注意在最后明确关闭文件!它们是
Buffered*Streams,因此不关闭它们可能会导致 unflushed 最后写入... -
你需要
flush你的缓冲区。这会将缓冲区中剩余的所有剩余数据写入您的流中。 -
您确定您的代码正确吗?你读到了
buffered而不是bufferedIn。您似乎过于简化了您的代码......请给我们原始代码。你真的要关闭BufferedOutputStream吗? -
我确实关闭了它,我需要冲洗它吗??
标签: java android inputstream