写入文件时插入换行符?

所以我的代码看起来像这样:

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 } } 

我在System.out.println(m.group(1));System.out.println(m.group(1));得到正确的输出formsSystem.out.println(m.group(1)); 但是当我稍后想写m.group(1)所显示的m.group(1)它写入文件而不放置换行符,因为代码没有。

只需调用fw.write(System.getProperty("line.separator"));

System.getProperty("line.separator")将为您的平台提供行分隔符(无论是Windows还是某些Unix风格)。

println(text)将换行符添加到字符串中,与print(text); print(System.getProperty("line.separator"));基本相同print(text); print(System.getProperty("line.separator")); print(text); print(System.getProperty("line.separator"));

所以为了添加换行符,你必须这样做。

但是,为了改进您的代码,我有两个建议:

  1. 不要在循环中创建新的FileWriter 。 在循环外创建它并在循环后关闭它。
  2. 不要使用FileWriter ,而是使用围绕FileWriterPrintWriter 。 然后你得到与println()相同的println()方法。

做就是了

 fw.write("\n"); 

这将为新行添加转义字符

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