简体   繁体   English

写入文件时插入换行符?

[英]Insert line break when writing to file?

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)); 我在System.out.println(m.group(1));System.out.println(m.group(1));得到正确的输出形式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. 但是当我后来想写m.group(1)所显示的m.group(1)它写入文件而不放置换行符,因为代码没有。

Just call fw.write(System.getProperty("line.separator")); 只需调用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). System.getProperty("line.separator")将为您的平台提供行分隔符(无论是Windows还是某些Unix风格)。

println(text) adds the line break to the string, and is essentially the same as print(text); print(System.getProperty("line.separator")); println(text)将换行符添加到字符串中,与print(text); print(System.getProperty("line.separator"));基本相同print(text); print(System.getProperty("line.separator")); 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. 不要在循环中创建新的FileWriter 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 . 不要使用FileWriter ,而是使用包装在FileWriter周围的PrintWriter Then you get the same println() method as System.out . 然后你会得到同样println()方法System.out

just do 做就是了

fw.write("\n");

that will put an escape character for a new line 这将为新行添加转义字符

您可以使用System.getProperty(“line.separator”)代替System.lineSeparator()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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