将javafx textarea写入包含换行符的文本文件

时间:2018-06-13 14:45:21

标签: java javafx text-files formatter

所以我现在正在尝试使用formatter类将javafx textarea的内容保存到文本文件中。问题是文本只是保存在一行中,没有任何换行符。

这是我用于写入textFile的代码

 File file = new File(link);
                    Formatter formatter = null;
                    try {
                        formatter = new  Formatter(file);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    formatter.format(textArea.getText() + "\n");

编辑: 我发现了问题:这是Windows Notepad的错误。当我在像notepadd ++这样的其他texteditor中打开txt文件时,它可以正常工作

3 个答案:

答案 0 :(得分:1)

你真的需要使用Formatter课吗?我想这个类在格式参数的内容中为%n占位符(但似乎忽略换行符)生成行分隔符(仅参见相应的javadoc):

format(String format, Object... args)
// Writes a formatted string to this object's destination using the specified format string and arguments.

一种解决方案可能是将格式字符串指定为"%s%n"(表示您要格式化字符串,后跟换行符)并传递TextArea的内容,例如: formatter.format("%s%n", textArea.getText()),如果确实需要使用格式化程序。

否则,你也可以通过一些Writer直接将textArea的内容输出到文件中:

FileWriter w = new FileWriter(file);
w.write(textArea.getText());
w.close();

答案 1 :(得分:0)

你必须关闭格式化程序

formatter.close();

格式化程序输出首先在内存中缓冲。因此,一旦完成,您必须关闭格式化程序。

使用finally块来实现此目的

    try {
        //code
    } catch{
     //code
    }
    finally {
        formatter.close();
    }

答案 2 :(得分:0)

在我的项目中,我按如下方式编写TextArea的内容:

byte[] contents = area.getText().getBytes(StandardCharsets.UTF_8);
Files.createDirectories(path.getParent());
Files.write(path, contents, StandardOpenOption.CREATE);

将内容保存为UTF-8编码的文本文件。这包括\n。鉴于我在Linux上工作,我没有检查它是否真的\n\r,我的胆量告诉我它只是\n

相关问题