2011-04-16 163 views
0

我想獲得一個簡單的Hello World txt文件,然後通過我的android應用程序讀取。在查看DDMS文件資源管理器時,它成功地創建了文本文件,但是當我嘗試讀取它時,我得到一個FileNotFoundException。Android模擬器寫入文件,但無法找到目錄

try { 

     final String TESTSTRING = new String("Hello World"); 

     FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 

     osw.write(TESTSTRING); 
     osw.flush(); 
     osw.close(); 

     FileInputStream fIn = new FileInputStream("test.txt"); 
     InputStreamReader isr = new InputStreamReader(fIn); 

     char[] inputBuffer = new char[TESTSTRING.length()]; 

     isr.read(inputBuffer); 

     String readString = new String(inputBuffer); 

     boolean isTheSame = TESTSTRING.equals(readString); 

     Log.i("File Reading Stuff", "success = " + isTheSame); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

也是錯誤的是java.io FileNotFoundException: /test.txt (No such file or directory)

任何幫助感謝。

回答

2

我不知道openFileOutput在哪裏保存它的文件,但是不會用它的輸入等效於openFileInput來讀取這樣的文件嗎?

+0

'openFileOutput()'目錄保存其文件由'getFilesDir()'標識。 OP應該按照你的建議使用'openFileInput()'或者使用'getFilesDir()'來構建一個有效的'File'對象到正確的位置,以便能夠直接使用'FileInputStream'。 – CommonsWare 2011-04-16 19:24:42

0

見我以前的帖子關於如何讀取信息/寫在Android的外部存儲目錄:

Android how to use Environment.getExternalStorageDirectory()

- 丹

+0

我試圖使用虛擬SD卡,但我不斷收到'java.io.FileNotFoundException:/mnt/sdcard/sdTest.txt(權限被拒絕)' – 2011-04-16 20:28:43

+0

您需要添加權限以將SD卡寫入應用程序的清單中 - 特別是:WRITE_EXTERNAL_STORAGE。如果你不打算寫任何東西,那麼你需要打開你的文件只讀 – debracey 2011-04-19 00:58:50

相關問題