文件使用字符串读写

时间:2015-11-03 05:35:12

标签: android android-activity

我收到错误:" 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);
}

2 个答案:

答案 0 :(得分: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"/>

答案 1 :(得分:0)

您应该在外部存储中写入,然后确保创建该文件。