如何在Java中将换行符写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19084352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:57:40  来源:igfitidea点击:

How to write new line character to a file in Java

javanewline

提问by user2192774

I have a string that contains new lines. I send this string to a function to write the String to a text file as:

我有一个包含新行的字符串。我将此字符串发送到一个函数以将字符串写入文本文件,如下所示:

    public static void writeResult(String writeFileName, String text)
    {
        try
        {
        FileWriter fileWriter = new FileWriter(writeFileName);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write(text);

        // Always close files.
        bufferedWriter.close();

        }
        catch(IOException ex) {
            System.out.println("Error writing to file '"+ writeFileName + "'");}
    } //end writeResult function

But when I open the file, I find it without any new lines. When I display the text in the console screen, it is displayed with new lines. How can I write the new line character in the text file.

但是当我打开文件时,我发现它没有任何新行。当我在控制台屏幕中显示文本时,它会以新行显示。如何在文本文件中写入换行符。

EDIT:Assume this is the argument textthat I sent to the function above:

编辑:假设这是text我发送给上述函数的参数:

I returned from the city about three o'clock on that
may afternoon pretty well disgusted with life.
I had been three months in the old country, and was

How to write this string as it is (with new lines) in the text file. My function write the string in one line. Can you provide me with a way to write the text to the file including new lines ?

如何在文本文件中按原样(使用新行)编写此字符串。我的函数将字符串写在一行中。你能给我提供一种将文本写入文件的方法,包括新行吗?

EDIT 2:The text is originally in a .txt file. I read the text using:

编辑 2:文本最初位于 .txt 文件中。我使用以下方法阅读文本:

while((line = bufferedReader.readLine()) != null)
{
sb.append(line); //append the lines to the string
sb.append('\n'); //append new line
} //end while

where sbis a StringBuffer

sbStringBuffer在哪里

回答by nhgrif

bufferedWriter.write(text + "\n");This method can work, but the new line character can be different between platforms, so alternatively, you can use this method:

bufferedWriter.write(text + "\n");此方法可以工作,但换行符可能因平台而异,因此,您也可以使用此方法:

bufferedWriter.write(text);
bufferedWriter.newline();

回答by JustDanyul

The BufferedWriter class offers a newLine()method. Using this will ensure platform independence.

BufferedWriter 类提供了一种newLine()方法。使用这将确保平台独立性。

回答by lreeder

In EDIT 2:

编辑 2 中:

while((line = bufferedReader.readLine()) != null)
{
  sb.append(line); //append the lines to the string
  sb.append('\n'); //append new line
} //end while

you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:

您正在阅读文本文件,并为其添加换行符。不要附加换行符,它不会在一些头脑简单的 Windows 编辑器(如记事本)中显示换行符。而是使用以下方法附加特定于操作系统的行分隔符字符串:

sb.append(System.lineSeparator());(for Java 1.7 and 1.8) orsb.append(System.getProperty("line.separator"));(Java 1.6 and below)

sb.append(System.lineSeparator());对于 Java 1.7 和 1.8sb.append(System.getProperty("line.separator"));Java 1.6 及以下

Alternatively, later you can use String.replaceAll()to replace "\n"in the string built in the StringBuffer with the OS-specific newline character:

或者,稍后您可以使用特定于操作系统的换行符String.replaceAll()替换"\n"StringBuffer 中内置的字符串:

String updatedText = text.replaceAll("\n", System.lineSeparator())

String updatedText = text.replaceAll("\n", System.lineSeparator())

but it would be more efficient to append it while you are building the string, than append '\n'and replace it later.

但是在构建字符串时附加它会比'\n'稍后附加和替换它更有效。

Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.

最后,作为开发人员,如果您使用记事本查看或编辑文件,您应该放弃它,因为有更多功能强大的工具,例如Notepad++或您最喜欢的 Java IDE。

回答by user3205467

SIMPLE SOLUTION

简单的解决方案

File file = new File("F:/ABC.TXT");
FileWriter fileWriter = new FileWriter(file,true);
filewriter.write("\r\n");

回答by User123456

Split the string in to string array and write using above method (I assume your text contains \n to get new line)

将字符串拆分为字符串数组并使用上述方法写入(我假设您的文本包含 \n 以获取新行)

String[] test = test.split("\n");

and the inside a loop

和内部循环

bufferedWriter.write(test[i]);
bufferedWriter.newline();

回答by élektra

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name")and System.getProperty("os.version").Example:

这是获取当前平台默认换行符的代码段。使用 System.getProperty("os.name")System.getProperty("os.version").示例:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("os.name").toLowerCase();
    if(os.contains("mac"){
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
    }
    if(os.contains("nix"))
        eol = "\n";
    if(os.contains("win"))
        eol = "\r\n";

    return eol;
}

Where eol is the newline

eol 是换行符的地方

回答by user1447901

Put this code wherever you want to insert a new line:

将此代码放在要插入新行的任何位置:

bufferedWriter.newLine();

回答by Rahul k

This approach always works for me:

这种方法总是对我有用:

String newLine = System.getProperty("line.separator");
String textInNewLine = "this is my first line " + newLine + "this is my second 
line ";

回答by Tarit Ray

    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();