我有以下代碼用於將文件從url下載到SD卡。此代碼適用於小文件,但是當文件大小很大時,我得到的下載文件大小爲0. 任何幫助,將不勝感激。下載顯示大小爲0的SD卡中的文件
Java代碼的
setContentView(R.layout.activity_download_file);
String exStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(exStorageDirectory, "Folder");
folder.mkdir();
File file = new File(folder, "scjp.pdf");
try {
if (!file.exists()) {
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
downloadFile(
"http://java.net/downloads/jfjug/SCJP%20Sun%20Certified%20Programmer%20for%20Java%206-0071591060.pdf",
file);
}
private void downloadFile(String fileUrl, File directory) {
try {
FileOutputStream fileOutput = new FileOutputStream(directory);
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
byte buffer[] = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, len);
}
fileOutput.close();
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我認爲你應該把下載的AsyncTask或線程 – Gyonder 2013-03-05 08:57:34
+1爲SCJP書 – Jacob 2013-03-05 09:03:09
@Gyonder可以請你告訴我wathz這裏的問題爲什麼對於大文件顯示文件下載0? – sonia 2013-03-05 09:07:49