简体   繁体   中英

Why isn't the FileWriter not creating a new line like it should? JAVA

Hi I have looked up how to create a new line when appending to a file many people say to use .write("\\n") before you append to the file but that doesn't work or even at the end of your .write() but nothing works. Other people say to use FileWriter fr = new FileWriter(file, true); but that does not work. Is there something that I am doing incorrectly?

文件未创建新行

try {
    String fileName = JOptionPane.showInputDialog(null, "Please enter the student ID that this grade belongs to");
    FileWriter writer = new FileWriter("Grades\\"+ fileName +".txt");
    BufferedWriter bw = new BufferedWriter (writer);
    File file = new File("Activity Log\\Activity Log.txt");
    FileWriter fr = new FileWriter(file, true);
    fr.write("Grade for student " + fileName + " has been posted.");
    fr.close();
    jTextArea1.write(bw);
    bw.close();
    jTextArea1.setText("");
    jTextArea1.requestFocus();

    frmGrades.dispose();

    ProfessorAccount.main(null);
}
catch(Exception e1) {
    JOptionPane.showMessageDialog(null, e1);
}

On Unix a \\n is used as a new line however on Windows you need \\r\\n ie two control characters.

Many editors cope with either so it doesn't matter but Notepad is very basic and only accepts Windows newlines.

One way to ensure you always write the platform specific new line is to wrap the FileWriter with a PrintWriter and use println

Line endings are system-dependent. You should either use a higher-level class to write to the file, or send the system-local ending, for example like so:

fr.write("Grade for student " + fileName + " has been posted." + System.lineSeparator());

The \\n escapes a newline in most Unix variants, but may not work on other machines.

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