2015-11-03 38 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