【发布时间】:2014-10-21 11:46:33
【问题描述】:
当我尝试从服务器下载文件时,它会丢失一些字节!并显示为损坏的文件。在我尝试从 URL 下载的代码下方。运行时也不例外。我在服务中使用它。 这些是我尝试的示例结果:
文件 1: 实际大小 = 73.2 kb 下载大小 = 68.7 kb
文件 2: 实际大小 = 147 kb 下载大小 = 137 kb
文件 3: 实际大小 = 125 kb 下载大小 = 116.8 kb
请帮助我找到我的代码所需的更正。 谢谢,
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// Successful finished
Log.d("reaching", "reaching : DOWNLOAD FINISHED SUCCESSFULLY");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
除非您知道来源是文本,否则不要使用
Reader,如果是,您应该使用Writer来编写它。否则你应该使用输入和输出流。 -
感谢@EJP 的帮助,当我更改为输入和输出流时它可以工作
标签: android file download inputstreamreader