在Android API 22(Lollipop)和23(Marshmallow)中创建目录

时间:2015-11-01 15:40:43

标签: android

我正在开发一个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;
}

在Kitkat工作了。在Lollipop及其上面,它提供了未创建的文件

清单

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

1 个答案:

答案 0 :(得分:1)

最后我解决了。感谢@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;
}