簡體   English   中英

將帶有換行符的字符串寫入文件

[英]Write string with newlines to file

我有一個從TextArea獲得的字符串。 該字符串包括用戶輸入的換行符。 我想將整個字符串(包括那些換行符)寫入文件。

這就是我現在所擁有的:

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

我已經用谷歌搜索,但是我不知道如何解決我的問題。

朝這個方向看:

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

例如:

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

您的代碼應該沒有問題。

無論如何,如果您使用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