且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java的FileWriter中创建新行

更新时间:2022-10-23 10:11:55

如果要获取当前操作系统(例如Windows的\r\n)中使用的换行符,可以通过>

  • System.getProperty("line.separator");
  • 因为Java7 System.lineSeparator()
  • 或如Stewart所述,通过String.format("%n");
  • 生成它们

您还可以使用PrintStream及其println方法,该方法将在字符串的末尾自动添加与OS相关的行分隔符

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
//         ^^^^^^^ will add OS line separator after data 

(BTW System.out也是PrintStream的实例).

I have coded the following FileWriter:

try {
    FileWriter writer = new FileWriter(new File("file.txt"), false);

    String sizeX = jTextField1.getText();
    String sizeY = jTextField2.getText();
    writer.write(sizeX);
    writer.write(sizeY);

    writer.flush();
    writer.close();
} catch (IOException ex) {}

Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.

What can be done to solve this?

Thank you.

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by

  • System.getProperty("line.separator");
  • since Java7 System.lineSeparator()
  • or as mentioned by Stewart generate them via String.format("%n");

You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
//         ^^^^^^^ will add OS line separator after data 

(BTW System.out is also instance of PrintStream).