2012-11-02 84 views
1

這可能是一個簡單的破解,但我不明白爲什麼這段代碼不會導致在我的Android外部文件系統中創建一個新文件?該目錄正確創建,但不是文件,而是我得到一個java.io.FileNotFoundException:/ mnt/sdcard/Mydir/MyFile,任何人都可以看到問題是什麼原因,我不能看到它嗎?創建並存儲文件到外部存儲

 //Generate a unique filename using date and time 
    String fileName = "myFile_"+formatter_file_name.format(today)+".txt"; 

    //Get path to root 
    String root = Environment.getExternalStorageDirectory().toString(); 

    //Create(if not exists) directory in root in which to store the reports 
    File myDir = new File(root + "/myDir"); 
    myDir.mkdirs(); 

    //Create report file object 
    File file = new File (myDir, fileName); 

    //If file already exists delete id(this should not be able to happen) 
    if (file.exists()) file.delete(); 

    try { 
     FileOutputStream fout = new FileOutputStream(file); 
     OutputStreamWriter osw = new OutputStreamWriter(fout); 

     // Write the string to the file 
     osw.write("TEST STRING"); 

     //Ensure that everything has been written to the file and close 
     osw.flush(); 
     osw.close(); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    }  

我有正確的權限在我的表現,我將插入一個檢查,看看外部存儲空間可用於寫,但我dont't認爲這就是問題所在......

回答

0

試試這個

try { 
    File root = Environment.getExternalStorageDirectory(); 
    File myFile = new File(root +"/textfile.txt"); 
    myFile.createNewFile(); 

    FileOutputStream fOut = new FileOutputStream(myFile); 
    OutputStreamWriter myOutWriter = 
     new OutputStreamWriter(fOut); 
    myOutWriter.append("String entered in file"); 

    myOutWriter.close(); 
    fOut.close(); 
} catch (Exception e) { 
    Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show(); 

} 
+0

Okey,我會看看這個答案,看看它是否有幫助。 但爲什麼它被低估? – Robert

+0

我也沒有得到爲什麼這是downvoted。我有這個工作,,, 也你可以按照這http://hoodaandroid.blogspot.in/2012/07/reading-and-writing-data-to-sdcard.html獲得所有關於閱讀和寫作的細節到sdcard .. –

+0

我已經測試過您的代碼,它的功能就像一個魅力。這是我的代碼的兩個問題,首先我不調用這個方法myFile.createNewFile(),因此我得到一個FileNotFound異常。其次,我的文件名包含非有效字符(:),並且會給我FileException(無效參數)。這是一個簡單的錯誤;-) 我對你的解決方案進行投票,thx。 – Robert