我试图将数据保存到sdCard首先我试图在使用getExternalFilesDir的externalStorage上的app目录中私下保存它但是给了我nullPointerException所以我尝试了下面给出的其他方式它工作但是当我想将文件存储到我想要的自定义目录自己命名它给我错误:
FileOutputStream os;
dirName = "/mydirectory/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + dirName);
dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
File file = new File(dir, dirName+fileName);
os = new FileOutputStream(file);
}else{
os = context.openFileOutput(fileName, MODE_PRIVATE);
}
resizedBitmap.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
}
Run Code Online (Sandbox Code Playgroud)
错误日志:
java.io.FileNotFoundException:/mnt/sdcard/mvc/mvc/myfile2.png(没有这样的文件或目录)
您的目录"/ mnt/sdcard/mvc/mvc"可能不存在.如何更改路径以将图像存储在Environment.getExternalStorageDirectory()路径中然后从那里工作?
此外,正如Robert指出的那样,请确保您对清单中的外部存储具有写入权限.
编辑 - 创建目录:
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();
Run Code Online (Sandbox Code Playgroud)
然后你可以保存一个文件root + "/mvc/mvc/foo.png".
你有权要求写入SD卡吗?将以下字符串添加到应用程序清单:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12003 次 |
| 最近记录: |