Android的文件保存到外部存储 [英] Android saving file to external storage
问题描述
我有创建目录和保存在我的Android应用程序的文件给它一个小问题。我使用的这块code要做到这一点:
I have a little issue with creating a directory and saving a file to it on my android application. I'm using this piece of code to do this :
String filename = "MyApp/MediaTag/MediaTag-"+objectId+".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(mediaTagBuffer);
fos.flush();
fos.close();
但它抛出一个异常:
But it's throwing an exception :
java.io.FileNotFoundException:/mnt/sdcard/MyApp/MediaCard/MediaCard-0.png(没有这样的文件或目录)
java.io.FileNotFoundException: /mnt/sdcard/MyApp/MediaCard/MediaCard-0.png (No such file or directory)
在该行: FOS =新的FileOutputStream(文件);
如果我设置文件名:的MyApp / MediaTag - + OBJECTID +
它的工作,但如果我尝试创建,将文件保存到其它目录是抛出异常。因此,任何想法,我做错了吗?
If I set the filename to : "MyApp/MediaTag-"+objectId+"
it's working, but If I try to create and save the file to an another directory it's throwing the exception. So any ideas what I'm doing wrong?
和另外一个问题:有没有什么办法让我的私人文件,在外部存储使用户无法看到他们在画廊,只有当他连自己的设备作为磁盘驱动器
?
And another question: Is there any way to make my files private in external storage so user can't see them in gallery, only if he connect his device as Disk Drive
?
推荐答案
使用此功能,以节省您的位图SD卡
Use this function to save your bitmap in SD card
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
和清单中添加此
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
编辑:使用这条线,你可以看到在画廊查看保存的图片
By using this line you can able to see saved images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
看看这个链接也<一href="http://rajareddypolam.word$p$pss.com/?p=3&$p$pview=true">http://rajareddypolam.word$p$pss.com/?p=3&$p$pview=true
这篇关于Android的文件保存到外部存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!