简体   繁体   English

将带有换行符的字符串写入文件

[英]Write string with newlines to file

I have a string that I get from a TextArea. 我有一个从TextArea获得的字符串。 This string includes user input newlines. 该字符串包括用户输入的换行符。 I want to write the entire string (including those newlines) to a file. 我想将整个字符串(包括那些换行符)写入文件。

This is what I have now: 这就是我现在所拥有的:

        FileWriter fw = new FileWriter(nm + ".txt");
        PrintWriter pw = new PrintWriter(fw);
        pw.print(txt);
        pw.close();

I've googled but I have no clue as to how I could fix my problem. 我已经用谷歌搜索,但是我不知道如何解决我的问题。

See in this direction: 朝这个方向看:

 1. System.getProperty("line.separator");
 2. System.lineSeparator();

For example: 例如:

pw.print(txt.replace("\n", System.lineSeparator()).replace("\r\n", System.lineSeparator()));

You should have no problem with your code. 您的代码应该没有问题。

Anyway, if you use Java 7 you should use Files : 无论如何,如果您使用Java 7,则应该使用Files

final Path path = Paths.get(nm + ".txt");

try (
    BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8,
        StandardOpenOption.APPEND, StandardOpenOption.CREATE_NEW);
) {
    writer.write(txt);
    writer.flush();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM