在 Java 的 FileWriter 中创建一个新行 [英] Create a new line in Java's FileWriter

查看:32
本文介绍了在 Java 的 FileWriter 中创建一个新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下 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 normally, but it doesn't seem to work.

可以做些什么来解决这个问题?

What can be done to solve this?

谢谢.

推荐答案

如果你想获得当前操作系统中使用的换行字符,比如 for Windows, 你可以通过

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

  • System.getProperty("line.separator");
  • 自 Java7 System.lineSeparator()
  • 或者如斯图尔特提到的那样通过 String.format("%n");

您还可以使用 PrintStream 及其 println 方法,它会自动在字符串末尾添加操作系统相关的行分隔符

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 

(顺便说一句,System.out 也是 PrintStream 的实例).

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

这篇关于在 Java 的 FileWriter 中创建一个新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆