2015-11-01 57 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; 
} 
相關問題