简体   繁体   中英

Writing multiple lines to a new file in java?

When I open the newly written file in jGRASP, it contains many lines of text. 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.

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. I'd suggest getting Notepad++ as it's just much much better.

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 . The windows "notepad" app only recognizes that separator.

Java actually knows the default line separator for the system it's running on and makes it available via the system property 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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