[英]How to save downloaded file in internal storage in android studio?
我的应用程序中有一个下载按钮。当我按下下载按钮时,它会从提供的 url 下载音频文件。但问题是我想将文件保存在名为“DownloadTestFolder”的内部存储文件夹中,它显示错误。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:gravity="center" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Download" android:onClick="Download" android:id="@+id/download"/> </LinearLayout>
public class DownloadTest extends Activity { DownloadManager downloadManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.download_test); } public void Download(View view){ downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE); Uri uri=Uri.parse("My Url"); DownloadManager.Request request = new DownloadManager.Request(uri); try{ request.setDestinationInExternalPublicDir(getFilesDir()+"/DownloadTestFolder","/"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); Long reference = downloadManager.enqueue(request); }catch (Exception e){ /* Error } } }
DownloadManager
只能下载到external storage
,您需要实现自己的下载管理器。
使用此方法保存文件:
// DownloadFile AsyncTask
private class DownloadFile extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(URL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(mContext.getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
用法:
new DownloadFile().execute("url_here");
注意:我已经为图像类型文件添加了代码
你可以试试这个:
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE);
File file = new File(directory,”fileName”);
String data = “TEST DATA”;
FileOutputStream fos = new FileOutputStream(“fileName”, true); // save
fos.write(data.getBytes());
fos.close();
这会将文件写入设备的内部存储 (/data/user/0/com.yourapp/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.