我遇到以下问题。字符串变量打印在txt文件上
```
1 3 1.
```
实际上,它必须输出
```
1 1 1
1 2 1
1 3 1
```
我不知道,代码中的错误在哪里。似乎每次代码都在重写,最后一条语句也被重写了。有人能帮我吗
public class RankingExportTest {
private static final String LINE_SEPARATOR = "rn";
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;
}
在循环的每次迭代中打开和关闭PrintWriter
,每次都覆盖文件。在循环之前打开它,然后关闭它。
您正在用每一行覆盖一个文件。创建PrintWriter一次,写入所有输出,然后关闭它:
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();
}
}