2015-11-03 66 views
0

我得到了錯誤:「java.io.FileNotFoundException」,用於標準輸入和輸出文件。目的是爲一個文件寫入一個字符串,然後再讀取它。該文件似乎已被寫入,但未打開以供閱讀。文件沒有被打開的原因嗎?在下面的第二部分,閱讀文件,是問題所在。提前感謝您的任何建議。使用字符串讀取和寫入文件

public void test(View view){ 
    //writing part 
    String filename="file.txt"; 
    String string="Hello world!"; 

    FileOutputStream outputStream; 
    try { 
     outputStream=openFileOutput(filename,MODE_PRIVATE); 
     outputStream.write(string.getBytes()); 
     outputStream.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    //read part 
    FileInputStream inputStream; 
    int length = (int) filename.length(); 
    byte[] bytes=new byte[length]; 
    try { 
     inputStream=new FileInputStream(filename); 
     inputStream.read(bytes); 
     inputStream.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    String data = new String(bytes); 
} 
+0

如果使用openFileOutput寫入文件,則使用openFileInput從中讀取。 – greenapps

+0

'int length =(int)filename.length();'。文件名的字符數?與文件大小無關。這是行不通的。 – greenapps

+0

這是錯誤的感謝。 「長度」已被替換爲512.我發現,如果將FileInputStream(filename)替換爲openFileInput(filename),代碼將起作用。輸入輸出對似乎是對稱的:openFileOutput-openFileInput。麻煩的是,讀取值是512字節,而原始字符串是簡單的,「你好,世界!」。 – gnoejh

回答

0

您好請嘗試下面的文件讀寫操作方法。希望它會幫助你

方法讀取文件作爲字符串

p_filePath = "your full file path"; 

public static String readFileAsString(String p_filePath) throws IOException, Throwable 
    { 
     String m_text; 
     BufferedReader m_br = new BufferedReader(new FileReader(p_filePath)); 
     try 
     { 
      StringBuilder m_sb = new StringBuilder(); 
      String m_line = m_br.readLine(); 
      while (m_line != null) 
      { 
       m_sb.append(m_line); 
       m_sb.append(File.separator); 
       m_line = m_br.readLine(); 
      } 
      m_text = m_sb.toString(); 
     } 
     finally 
     { 
      m_br.close(); 
     } 
     return m_text; 
    } 

寫入字符串方法文件

public static void writeStringToFile(String p_string, String p_fileName) throws CustomException 
    { 
     FileOutputStream m_stream = null; 
     try 
     { 
      m_stream = new FileOutputStream(p_fileName); 
      m_stream.write(p_string.getBytes()); 
      m_stream.flush(); 
     } 
     catch (Throwable m_th) 
     { 

     } 
     finally 
     { 
      if (m_stream != null) 
      { 
       try 
       { 
        m_stream.close(); 
       } 
       catch (Throwable m_e) 
       { 

       } 
       m_stream = null; 
      } 
     } 
    } 

添加下面的權限在你的清單還

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

OP正在寫入內部存儲器,因此不需要該權限。因爲他正在寫內部記憶,所以他使用相對路徑。不需要使用完整路徑。 – greenapps

0

您應該在外部存儲器中寫入,然後確保該文件是否已創建。

+0

OP爲什麼要寫入外部存儲器? – greenapps

+0

我爲此代碼使用內部存儲。 – gnoejh

相關問題