我想下载一个文件,然后将其保存到设备的SD卡中。我正在使用getExternalFilesDir(),这也是Android开发人员团队推荐的,但是当我运行我的应用程序时,会在两个位置(SD卡和内部存储器)中为应用程序包创建一个目录,但文件保存在内部存储器中。
答案 0 :(得分:0)
使用此主题下载:
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... Url) {
int count;
try {
URL url = new URL(Url[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
String folder_main = "TEST1";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
int lenghtOfFile = connection .getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Save the downloaded file
OutputStream output = new FileOutputStream(f + "/"
+ movie_name_b);
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 / fileLength));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
}
catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
}
}
执行:
new DownloadFile().execute(URL_TO_DOWNLOAD);
它将在SD卡中创建一个文件夹名称Test1。并且不要忘记在Manifest中添加权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:0)
您可以使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)将文件保存在SD卡的下载目录中。