-1

I have code that finds coordinates between specific words. Now, output to console works perfect, but id like to output the matches found TO FILE My current code:

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");

}

        }

Output should be

world

solid

(3245) (2334) (-234)

.

.

.

.

.

.

(457) (2) (2323)

instead, when i output to file, only the first coords appear:

(3245) (2334) (-234)

4

1 に答える 1

2

書かれているように、while ループを通過するたびに同じファイルを開いています。各FileWriter/BufferedWriterコンボは 1 行の出力を書き込みます。どれも閉じられたことはありません。それらが最終的に解放されると、どれが最後にフラッシュされて閉じられ、他のすべての出力が上書きされるかについての推測ゲームになります。

が作成された後、whileループを 内に移動してみてください。そして、完了したら閉じます(ブロック内がいいでしょう)。tryBufferedWriterbffinally

于 2013-05-19T16:36:01.887 に答える