可能重複:
Android:「Unexpected end of stream」 exception downloading large files下載文件時流結束錯誤?
我下載與下面的下面的代碼文件。該文件是大約。大小5MB。然而,當下載大約60-90%時,我得到了一個java.io.IOException「意外的流結束」錯誤。我不明白如何解決它,它讓我發瘋。
編輯:如果某人能夠在手機上成功下載文件,至少可以測試它嗎?這將允許我確定問題是我的手機還是代碼。
try {
URL url = new URL(full_url);
conexion = (URLConnection)url.openConnection();
conexion.setReadTimeout(20000);
conexion.connect();
File file = new File(root.getAbsolutePath()+"/", fileName);
int lenghtOfFile = conexion.getContentLength();
System.out.println("content-length-header is: " + lenghtOfFile);
InputStream input = conexion.getInputStream();
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[8192];
long total = 0;
contentView.setTextViewText(R.id.status_text,"Downloading file " + (78 - GlobalData.missingFiles.size()) + " of " + 77);
int downloadProgress = (int)((total*100)/lenghtOfFile);
int lastProgressUpdate=0;
while ((count = input.read(data)) != -1) {
System.out.println("available bytes:" + input.available());
total += count;
downloadProgress = (int)((total*100)/lenghtOfFile);
Log.e("totaltotal","" + (int)((total*100)/lenghtOfFile));
output.write(data,0,count);
if(downloadProgress%20==0 && downloadProgress != lastProgressUpdate) {
notification.contentView.setProgressBar(R.id.status_progress, 100,downloadProgress, false);
notificationManager.notify(1,notification);
lastProgressUpdate=downloadProgress;
}
if(downloadProgress == 100){
GlobalData.downloadFiles.add("" +fileName);
GlobalData.missingFiles.remove(fileName);
}
}
output.flush();
output.close();
input.close();
if(downloadProgress != 100){
File temp_file = new File(root.getAbsolutePath()+"/", fileName);
try{
if(temp_file.exists()){
boolean del_main = temp_file.delete();
Log.e("File","Does file exists: " + del_main);
Log.e("FilePath","PATH: " + temp_file.getAbsolutePath());
}else{
Log.e("File Exists NOT","NOT EXISTING");
}
}catch(Exception e){
Log.e("FileDelete","deleting is giving problems");
}
}
} catch (Exception e) {
Log.e("PRINTSTACK","STACK:" + e.getMessage());
e.printStackTrace();
System.out.println("Downloading didn't work");
killService();
}
「root」指向什麼? –
根指向SD卡中的文件夾 – bytebiscuit