InputStream - 处理网络更改

Tsi*_*kon 5 java android network-programming inputstream

我正在使用Java邮件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();
}
Run Code Online (Sandbox Code Playgroud)

处理这个问题的最佳方法是什么?谢谢.

use*_*421 1

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