我正在开发一个android应用程序,该应用程序要求将文件(图像)保存在设备上,以便以后访问。我需要创建一个目录(文件夹),然后把这些东西(图像)放进去我在API 19(Kitkat)上运行了这段代码,但在棒棒糖和最新的棉花糖上不起作用。
代码
String stored = null;
File sdcard = Environment.getExternalStorageDirectory() ;
File folder = new File(sdcard.getAbsoluteFile() , "PropertyImages");
Log.i("Folder Name",folder.toString());
if (folder.exists()){
Log.w("Folder Exist","Folder Exists");
}else{
Log.w("Folder NOT Exist","Folder NOT Exist");
}
if (folder.mkdir()){
Log.w("Folder Created","Folder Created");
}else{
Log.w("Folder is NOT Created","Folder is NOT Created");
}
File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
在基特成功了。在棒棒糖和以上它给文件没有创建
舱单
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
最后我解决了它。感谢@greenapps和@GreyBeardedGeek。@greenapp帮了我很多忙,让我对getExternalFilesDir()进行了研究和阅读这是我的解决方案,以防将来有人需要
public static String createExternalStoragePrivateFile(Bitmap bitmap,String imagename,Context ctx) {
File file = new File(ctx.getExternalFilesDir("PW"), imagename + "jpg");
String stored= "Stored";
try
{
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch(
IOException e
)
{
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing ");
}
return stored;
}