Android不会在文本文件中写新行

时间:2012-02-16 13:43:41

标签: java android android-file

我正在尝试在android中为文本文件写一个新行。

这是我的代码:

FileOutputStream fOut;
try {
    String newline = "\r\n";
    fOut = openFileOutput("cache.txt", MODE_WORLD_READABLE);
    OutputStreamWriter osw = new OutputStreamWriter(fOut); 

    osw.write(data);
    osw.write(newline);

    osw.flush();
    osw.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

我尝试了\n\r\n,我也尝试获取新行的系统属性,但这些属性都不起作用。

数据变量包含来自同一文件的先前数据。

String data = "";

try {
    FileInputStream in = openFileInput("cache.txt");   
    StringBuffer inLine = new StringBuffer();
    InputStreamReader isr = new InputStreamReader(in, "ISO8859-1");
    BufferedReader inRd = new BufferedReader(isr,8 * 1024);
    String text;

    while ((text = inRd.readLine()) != null) {
        inLine.append(text);
    }

    in.close();
    data = inLine.toString();
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

3 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,尝试了书中的每一个技巧。

我的问题:新行已经写好了,但在阅读时却被删除了:

while (readString != null) {
                datax.append(readString);
                readString = buffreader.readLine();
            }

该文件逐行读取并连接,因此换行消失。

我没有在记事本中查看原始文件,因为我不知道在手机上查看的位置,而我的日志屏幕使用了删除换行符的代码: - (

所以简单的灵魂就是在阅读时把它放回去:

while (readString != null) {
                datax.append(readString);
                datax.append("\n");
                readString = buffreader.readLine();
            }

答案 1 :(得分:0)

我执行了类似的程序,它对我有用。我观察到一种奇怪的行为。它将这些新行添加到文件中,但光标仍保留在第一行。如果您要验证,请在换行符后面写String,您会看到String写在新行的下方。

答案 2 :(得分:0)

我遇到了同样的问题而无法写新行。相反,我使用BufferdWritter在文件中写入一个新行,它对我有用。 这是一个示例代码片段:

OutputStreamWriter out = new OutputStreamWriter(openFileOutput("cache.txt",0));
BufferedWriter bwriter = new BufferedWriter(out);
// write the contents to the file
bwriter.write("Input String"); //Enter the string here
bwriter.newLine();