-1

I have got following Problem. The string variable prints on the txt file

```
 1 3 1.
```

Actually, it must outputs

```
1 1 1 
1 2 1
1 3 1
```

I don't know, where the error is in the Code. It seems to be that the code is overwriting everytime, and the last statement was overwrites. Can anyone helps me

public class RankingExportTest {
private static final String LINE_SEPARATOR = "\r\n";
Set<String> exportGraph(DirectedUnweightedGraph<CommonNode, CommonEdge<CommonNode>> graph) throws IOException {
Set<String> rows = new LinkedHashSet<>((int)graph.getEdgeCount());
for(CommonNode fromNode: graph.getNodes()) {
 for(CommonNode toNode: graph.adjacentTo(fromNode)) {
            String row = String.format(
                "%d %d 1",
                fromNode.getIdentity().intValue(),
                toNode.getIdentity().intValue()
            );
            rows.add(row);
           System.out.println(row);

            try {
                PrintWriter out;
                out = new PrintWriter( "/Users/......" );
                out.print(rows);
                out.close();
                //System.out.println(row);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    return rows;

}
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49

2 Answers2

0

You open and close the PrintWriter in each iteration of the loop, overwriting the file every time. Open it before the loop and close it after.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

You're overwriting a file with each row. Create PrintWriter once, write all output and then close it:

PrintWriter out = null;
try {
    out = new PrintWriter("path");
    for (CommonNode fromNode : graph.getNodes()) {
        for (CommonNode toNode : graph.adjacentTo(fromNode)) {
            String row = String.format("%d %d 1", fromNode.getIdentity().intValue(), toNode.getIdentity().intValue());
            rows.add(row);
            System.out.println(row);
            out.print(row);
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (out != null) {
        out.close();
    }
}
Keammoort
  • 3,075
  • 15
  • 20