5

所以我的代码如下所示:

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));但是,当我稍后想写它显示的内容时,m.group(1)它会写入文件而不放置换行符,因为代码没有换行符。

4

4 回答 4

27

只要打电话fw.write(System.getProperty("line.separator"));

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

于 2013-07-18T06:38:05.837 回答
1

做就是了

fw.write("\n");

这将为新行添加一个转义字符

于 2013-07-18T06:37:00.963 回答
1

println(text)在字符串中添加换行符,本质上与print(text); print(System.getProperty("line.separator"));.

因此,为了添加换行符,您必须执行相同的操作。

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

  1. 不要FileWriter在循环中创建新的。在循环外创建它并在循环后关闭它。
  2. 不要使用 a FileWriter,而是使用 aPrintWriter包裹 a FileWriter。然后你得到与 相同的println()方法System.out
于 2013-07-18T06:40:19.403 回答
1

您也可以使用System.getProperty("line.separator") System.lineSeparator()

于 2017-11-27T16:47:48.113 回答