【发布时间】:2013-01-04 10:36:32
【问题描述】:
我正在使用 Java 邮件 API 下载附件,每当网络状态发生微小变化时,我的应用就会卡住,我必须重新启动它,它甚至没有崩溃。 这是代码sn-p:
InputStream is = bodyPart.getInputStream();
String fileName = MimeUtility.decodeText(bodyPart.getFileName());
// Downloading the file
File f = new File(Constants.getPath() + fileName);
try {
FileOutputStream fos;
fos = new FileOutputStream(f);
byte[] buf = new byte[8*1024];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
}
处理此问题的最佳方法是什么?谢谢。
【问题讨论】:
-
尝试用
BufferedInputStream包装输入流,看看这里是否支持skip()方法(是否抛出IOException)。如果是,那么您将能够恢复之前的下载。 -
嗨,谢谢,它确实会抛出 IOException。您能否告诉我如何恢复之前的下载以及它与应用程序冻结的事实有何关系?
-
如果支持
skip(),则支持Resuming previous download。但是,我能想到的唯一选择是在is.read()上设置一个超时时间,如果碰巧超过了超时时间,那么您应该终止下载并重新开始。看到这个问题:stackoverflow.com/questions/804951/… -
@Eng.Fouad BufferedInputStream 完全支持 skip() :它不需要测试来确定;但是支持 skip() 的 BufferedInputStream 与支持恢复先前下载的 JavaMail 无关。他需要的是读取超时。我手头没有 JavaMail 文档,但它肯定支持。
-
@EJP According to the documentation,
skip()throwsIOExceptionif the stream does not support seek,这就是为什么我说“如果它支持skip(),那么它将支持Resuming previous download” .
标签: java android network-programming inputstream