【问题标题】:java (matcher.group()) - write to filejava (matcher.group()) - 写入文件
【发布时间】:2013-05-19 16:30:52
【问题描述】:

我有代码可以找到特定单词之间的坐标。 现在,输出到控制台工作完美,但我喜欢将找到的匹配输出到文件 我当前的代码:

public class Filetostring {


public static void main(String[] args) throws FileNotFoundException, IOException {
    String s = new Scanner(new File("input.txt")).useDelimiter("\\Z").next();
//System.out.println(content);


    Pattern patt;
    patt = Pattern.compile("\\bworld\\b|\\bsolid\\b|.(-?\\d+\\s-?\\d+\\s-?\\d+\\)\\s\\     (-?\\d+\\s-?\\d+\\s-?\\d+\\)\\s\\(-?\\d+\\s-?\\d+\\s-?\\d+).");
    Matcher matcher = patt.matcher(s);
while(matcher.find())
//System.out.println(matcher.group());


try (FileWriter file2 = new FileWriter("output.txt"); 
        BufferedWriter bf = new BufferedWriter(file2)) {
        bf.write(matcher.group());
}

        System.out.println("Done");

}

        }

输出应该是

世界

固体

(3245) (2334) (-234)

.

.

.

.

.

.

(457) (2) (2323)

相反,当我输出到文件时,只出现第一个坐标:

(3245) (2334) (-234)

【问题讨论】:

    标签: java string file matcher


    【解决方案1】:

    正如所写,您在每次通过 while 循环时打开同一个文件。每个FileWriter/BufferedWriter 组合将写入一行输出。没有一个是关闭的。当它们最终被释放时,这将是一场猜谜游戏,最后一个被刷新和关闭,覆盖所有其他输出。

    在创建BufferedWriter 之后,尝试将while 循环移动到try 内。然后在完成后关闭bf(在finally 块中会很好)。

    【讨论】:

    • 谢谢,成功了。唯一的问题是输出在一行中
    • 尝试使用 PrintWriter 及其println 方法。见docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
    • 效果很好! PrintWriter bf = new PrintWriter(file2)) { while (matcher.find()) bf.println(matcher.group()); bf.close();
    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2012-12-11
    • 2014-08-01
    • 2016-01-30
    相关资源
    最近更新 更多