我製作了一個Android應用程序,用於從服務器下載文件並將其保存到內部存儲器的目錄中。首先代碼驗證鏈接是否存在以及鏈接是否存在,然後下載文件。該文件正在下載,但當我去文件夾,看看文件是否存在,文件存在,但這不是我放在服務器上的文件。一切正常的的AsyncTaskAndroid-文件從服務器下載,但使用不同的文件名和擴展名保存
這裏去我的代碼裏面:
String fileName = "abc.pdf";
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/MyApp/");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
使用:https://github.com/smanikandan14/ThinDownloadManager –
'的OutputStream輸出=新FileOutputStream中(環境 .getExternalStorageDirectory()的toString() +「/ MyApp的/「);'。當/ MyApp /是一個文件夾時,你根本沒有文件名。當然,你可以放任何你想要的文件名:OutputStream output = new FileOutputStream(環境 .getExternalStorageDirectory()。toString() +「/MyApp/myfilename.jpg」); – greenapps