我正在使用Java郵件API下載附件,並且每當網絡狀態發生小的變化時,我的應用程序就會卡住,我必須重新啓動它,甚至不會崩潰。 這是代碼片段:InputStream - 處理網絡更改
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。你會好心告訴我,我怎樣才能恢復以前的下載,它是如何與應用程序凍結的事實有關? – Tsikon
如果它支持'skip()',那麼它將支持'恢復以前的下載'。然而,我能想到的唯一選擇是對'is.read()'有一個超時,如果它恰好超過了超時時間,那麼你應該終止下載並重新開始。看到這個問題:http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-inputstream-with-a-timeout –