天天看點

android中奇怪的FileNotFoundException

寫了一段代碼 其作用是往SDCard裡面寫一張照片的資料。 

到也沒覺的有多難,直接就用字元串拼出來路徑和檔案名,然後建立。但是就是會報錯。代碼如下:

String name = "test.jpeg";
File picFile = new File(Environment.getExternalStorageDirectory().toString()+
File.separator +"testCamera"+ File.separator + name);//直接建立從路徑到檔案名的File對象

try {
    //FileOutputStream方法會在指定檔案不存在的情況下自動建立
    FileOutputStream fos = new FileOutputStream(picFile);
    fos.write(data);
} catch (Exception e) {
          // TODO Auto-generated catch block
    e.printStackTrace();
}
           

但是上面這段代碼就是會抛出異常

java.io.FileNotFoundException: /mnt/sdcard/testCamera/test.jpeg(No such file or directory)

讓我十分的奇怪

查了下資料 加上了android中的寫SDCard的權限

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

還是不行 依然報錯。郁悶壞我了,接着查,終于在Stack Overflow上找到同患難的兄弟們

他們的解決方法也讓我有點奇怪

将整個檔案串劃分為兩段,一段是目錄名,一段是檔案名,然後分開建立,就可以了。于是我修改代碼如下

String name= "test.jpeg";
File picFileDir = new File(Environment.getExternalStorageDirectory().toString()+
File.separator +"testCamera");//僅建立路徑的File對象

if(!picFileDir.exists()){
    picFileDir.mkdir();//如果路徑不存在就先建立路徑}

File picFile = new File(picFileDir,name);//然後再建立路徑和檔案的File對象

try {
    //FileOutputStream方法會在指定檔案不存在的情況下自動建立
    FileOutputStream fos = new FileOutputStream(picFile);
    fos.write(data);

} catch (Exception e) {
              // TODO Auto-generated catch block
            e.printStackTrace();
}
           

ok問題解決了!誰能解釋下為什麼?為什麼一定要分開建立,奇怪!