Java InputStream-处理网络更改

Java InputStream-处理网络更改,java,android,network-programming,inputstream,Java,Android,Network Programming,Inputstream,我正在使用Java mail API下载附件,每当网络状态发生微小变化时,我的应用程序就会卡住,我必须重新启动它,它甚至不会崩溃。 这是代码片段: InputStream is = bodyPart.getInputStream(); String fileName = MimeUtility.decodeText(bodyPart.getFileName()); // Downloading the file File f = new File(Constants.getPath() +

我正在使用Java mail API下载附件,每当网络状态发生微小变化时,我的应用程序就会卡住,我必须重新启动它,它甚至不会崩溃。 这是代码片段:

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();
}

处理这个问题的最佳方式是什么?谢谢。

您的应用程序被卡住了。解决方法是设置读取超时,如中所述。如果发生超时,将抛出SocketTimeoutException。

尝试使用
BufferedInputStream
包装输入流,并查看此处是否支持
skip()
方法(它是否引发IOException)。如果是,那么您将能够恢复以前的下载。您好,谢谢,它确实会引发IOException。请告诉我如何恢复以前的下载,以及它与应用程序冻结的事实有何关系?如果它支持
skip()
,那么它将支持
恢复以前的下载。但是,我能想到的唯一选择是在
is.read()
上有一个超时,如果它恰好超过了超时时间,那么您应该终止下载并重新开始。看看这个问题:@Eng.Fouad BufferedInputStream本身就支持skip():它不需要测试来确定这一点;但是BufferedInputStream支持skip()与支持恢复先前下载的JavaMail无关。他需要的是读取超时。我手头没有JavaMail文档,但它肯定支持这一点。@EJP,
skip()
抛出
IOException
如果流不支持seek,这就是为什么我说“如果它支持
skip()
,那么它将支持
恢复以前的下载
”。我有以下所有超时:props2.setProperty(“mail.imaps.connectionpooltimeout”,“3000”);props2.setProperty(“mail.imaps.connectiontimeout”,“3000”);props2.setProperty(“mail.imap.timeout”,“3000”);当获取消息详细信息时,它仍然会阻塞,例如Message.getSubject()。奇怪的是,只有从3g切换到WI-FI时才会发生这种情况。当我从WI-FI切换到3g时,它会引发FolderClosedException,然后我就可以处理此问题。谢谢,我通过在timeout属性中将imap更改为imap解决了此问题。