2015-11-01 60 views
0

我正在开发一个android应用程序,需要将文件(图像)保存在设备上以便稍后访问它们。我需要创建一个目录(文件夹),然后把这些东西(图像)在其中 我有这个代码运行API 19(Kitkat),但不适用于棒棒糖和最新的棉花糖。在Android API 22(棒棒糖)和23(棉花糖)中创建目录

代码

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"/> 
+0

你忘了告诉-in words-哪个目录你使用。 – greenapps

+0

将您的文件置于getExternalFilesDir(s)之一中。 – greenapps

+0

@greenapps,请你可以给我看一个代码参考。我似乎不明白。谢谢我的男人 – devloper2009

回答

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; 
} 
相关问题