2011-08-11 66 views
2

我想寫一個位圖在Android上的SD卡,我得到我宣佈在清單中的android.permission.WRITE_EXTERNAL_STORAGE許可
/mnt/sdcard/PhysicsSketchpad/sketchpad145.png (No such file or directory).
錯誤信息,這是我的代碼:的Android寫的位圖到SD卡

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
         "/PhysicsSketchpad/"; 
File dir = new File(file_path); 
dir.mkdirs(); 
File file = new File(dir, "sketchpad" + pad.t_id + ".png"); 
FileOutputStream fOut = new FileOutputStream(file); 

bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut); 
fOut.flush(); 
fOut.close(); 

發生了什麼事?

UPDATE

它好像當我嘗試寫現有的目錄,我得到否定錯誤的許可,

08-11 09:55:23.796: WARN/Physics Sketchpad(8881): Error when saving: IOException /mnt/sdcard/download/sketchpad54.png (Permission denied) 

,當我嘗試在保存新目錄我得到一個沒有這樣的文件或目錄錯誤,
08-11 09:59:20.175: WARN/Physics Sketchpad(9040): Error when saving: IOException /mnt/sdcard/PhysicsSketchpad/sketchpad55.png (No such file or directory)

另外,File.mkdirs()根據成功與否返回布爾值,並返回false。

+2

我發現這個問題!我的使用許可標籤位於我的應用程序標籤中。雖然它沒有直接解決我的問題,但Ilango的回答和評論對我最有幫助。 – zim333311

回答

4

試試這段代碼。

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
          "/PhysicsSketchpad"; 
    File dir = new File(file_path); 
if(!dir.exists) 
    dir.mkdirs(); 
    File file = new File(dir, "sketchpad" + pad.t_id + ".png"); 
    FileOutputStream fOut = new FileOutputStream(file); 

    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut); 
    fOut.flush(); 
    fOut.close(); 
+0

我試過你的代碼,它給了我同樣的錯誤。 – zim333311

+0

你想使用模擬器或設備嗎?如果設備,你插入了SD卡還是模擬器,你有沒有添加SD卡? –

+0

你可以發佈那個錯誤消息嗎? –

0

你得到的絕對路徑檢查到錯誤,你得到什麼路徑

/mnt/sdcard/AppName/appname145.png 

,並設置了

Environment.getExternalStorageDirectory().getAbsolutePath() + 
         "/PhysicsSketchpad/"; 

這裏爲「PhysicsSketchpad」 DIR不在上述路徑獲得

試一試

Environment.getExternalStorageDirectory().toString()+ "/PhysicsSketchpad/"; 
+0

我試圖在代碼中編輯我的程序的名稱以使其更通用,但我忘記將其更改爲一半。我編輯回來。 – zim333311

3

試試這段代碼。這對我有效。

public void saveBitmap(Bitmap bm) 
{ 
    try 
    { 
     String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/"; 
     String mFilePath = mBaseFolderPath + "abcd.jpg"; 

     FileOutputStream stream = new FileOutputStream(mFilePath); 
     bm.compress(CompressFormat.JPEG, 100, stream); 
     stream.flush(); 
     stream.close(); 
    } 
    catch(Exception e) 
    { 
     Log.e("Could not save", e.toString()); 
    } 
} 

詞shash

+0

我試過了你的代碼,但是我得到了同樣的錯誤。 – zim333311

+0

你能分享logcat消息嗎?/mnt/sdcard/PhysicsSketchpad文件夾是否存在? – Shash316

+0

對不起,關於上面的帖子,這是你的代碼的一個不同的錯誤。在IOException catch中寫道:'Log.w(「Physics Sketchpad」,「Error saving when save:IOException」+ e.getLocalizedMessage());',它給出了一個logcat消息** 08-11 00:27:04.326 :警告/物理畫板(12994):保存時出錯:IOException /mnt/sdcard/DCIM/Camera/sketchpad152.jpg(權限被拒絕)**。與其他代碼,我得到錯誤消息** 08-11 00:29:30.116:警告/物理畫板(13140):保存時出錯:IOException /mnt/sdcard/PhysicsSketchpad/sketchpad153.png(沒有這樣的文件或目錄)** – zim333311