Insert line break when writing to file?

一曲冷凌霜 提交于 2019-12-30 07:05:25

问题


So My code looks like this:

try {
    while ((line = br.readLine()) != null) {
        Matcher m = urlPattern.matcher (line);
        while (m.find()) {
            System.out.println(m.group(1));

            //the println puts linebreak after each find

            String filename= "page.txt";
            FileWriter fw = new FileWriter(filename,true);
            fw.write(m.group(1));
            fw.close();

            //the fw writes everything after each find with no line break
    }
}

I get right form of output at line System.out.println(m.group(1)); However when I later on want to write what is shown by m.group(1) It writes to file without putting linebreak since the code doesn't have one.


回答1:


Just call fw.write(System.getProperty("line.separator"));.

System.getProperty("line.separator") will give you the line separator for your platform (whether Windows or some Unix flavor).




回答2:


println(text) adds the line break to the string, and is essentially the same as print(text); print(System.getProperty("line.separator"));.

So in order to add the line break you have to do the same.

However, to improve your code, I have two recommendations:

  1. Don't create a new FileWriter in the loop. Create it outside the loop and close it after the loop.
  2. Don't use a FileWriter, but instead a PrintWriter wrapped around a FileWriter. Then you get the same println() method as System.out.



回答3:


just do

fw.write("\n");

that will put an escape character for a new line




回答4:


You can use instead System.getProperty("line.separator") also System.lineSeparator()



来源:https://stackoverflow.com/questions/17716192/insert-line-break-when-writing-to-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!