2013-02-16 65 views
0

上午使用此代碼來創建和寫入SD卡上的文件,但運行我的Android應用程序後,我似乎無法找到在SD卡中創建的任何文件。我不確定我的代碼是否有問題或者什麼。請幫幫我。任何意見將不勝感激..謝謝!在SD卡中創建的文件丟失?

這裏是我使用的代碼:

private void writeToSDFile() { 


    File root = android.os.Environment.getExternalStorageDirectory(); 
    tv.append("\nExternal file system root: "+root); 



    File dir = new File (root.getAbsolutePath()); 
    dir.mkdirs(); 
    File file = new File(dir, "wordlist.txt"); 

    try {  



     FileOutputStream f = new FileOutputStream(file); 


     PrintWriter pw = new PrintWriter(f); 
     pw.println(stringword); 
     pw.append(stringword); 


     pw.flush(); 
     pw.close(); 
     f.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     Log.i(TAG, "******* File not found.); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    tv.append("\n\nFile written to "+file); 

}//end writeToSDFile 
+0

任何錯誤顯示?你有WRITE_EXTERNAL_STORAGE權限嗎? – StarPinkER 2013-02-16 02:40:00

回答

0

沒有什麼錯,似乎在你的代碼,你必須做出的兩件事情肯定:

1 - 你有相應的權限你的清單即WRITE_EXTERNAL_STORAGE

2-外部存儲是mounted eg

if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){ 
    // write your file 
} 

您的代碼冗餘,行File dir = new File (root.getAbsolutePath());是絕對無用的。

所有你需要的是:

File file = new File(Environment.getExternalStorageDirectory(), "wordlist.txt"); 
+0

我已經在清單中寫了WRITE_EXTERNAL_STORAGE權限,但是,我所觀察到的是我的txtView中顯示的目錄是mnt/sdcard /。這是什麼意思? – chArm 2013-02-16 02:57:38

+0

感謝您的回覆,我相信我有關於SD卡掛載的問題。我會盡力讓它現在工作。謝謝你@iTech =) – chArm 2013-02-16 03:11:55

相關問題