简体   繁体   English

在java中将多行写入新文件?

[英]Writing multiple lines to a new file in java?

When I open the newly written file in jGRASP, it contains many lines of text. 当我在jGRASP中打开新写入的文件时,它包含许多行文本。 When I open the same text file in notepad, it contains one line of text with the same data. 当我在记事本中打开相同的文本文件时,它包含一行具有相同数据的文本。 The transFile is just a variable for the name of the text file that I am making. transFile只是我正在制作的文本文件名的变量。

FileWriter f = new FileWriter(transFile, true);
BufferedWriter out = new BufferedWriter(f);
out.write(someOutput + "\n");
out.close();
f.close();

I have changed the code to the following and it fixed the problem in notepad. 我已将代码更改为以下内容并修复了记事本中的问题。

out.write(someOutput + "\r\n");

Why does this happen? 为什么会这样?

\\r\\n is the windows carriage return, which is what notepad will recognize. \\ r \\ n是windows回车,这是记事本会识别的。 I'd suggest getting Notepad++ as it's just much much better. 我建议使用Notepad ++,因为它要好得多。

You could do it this way also: 你也可以这样做:

public void appendLineToFile(String filename, String someOutput) {        
    BufferedWriter bufferedWriter = null;        
    try {            
        //Construct the BufferedWriter object
        bufferedWriter = new BufferedWriter(new FileWriter(filename));            
        //Start writing to the output stream
        bufferedWriter.append( someOutput );
        bufferedWriter.newLine();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        //Close the BufferedWriter
        try {
            if (bufferedWriter != null) {
                bufferedWriter.flush();
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

The default line separator for windows (historically) is \\r\\n . Windows的历史行分隔符(历史上)是\\r\\n The windows "notepad" app only recognizes that separator. Windows“记事本”应用程序识别该分隔符。

Java actually knows the default line separator for the system it's running on and makes it available via the system property line.separator . Java实际上知道它运行的系统的默认行分隔符,并通过系统属性line.separator使其可用。 In your code you could do: 在您的代码中,您可以:

...
out.write(someOutput);
out.newLine();
...

the newLine() method appends the system's line separator as defined in that property. newLine()方法追加系统在该属性中定义的行分隔符。

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

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