我正在开发一个程序,该程序使用 Dijkstra 算法并将结果记录到文本文件中。我写入文件的代码如下所示:
try (PrintWriter pr = new PrintWriter(filename + "Out.txt")) {
pr.println("Adjacency Matrix: " + (endTime - startTime) + " ms ");
pr.println("Min-Heap: ");
pr.println("Fibonnaci Heap:");
pr.println("Dijkstra Adjacency Matrix");
pr.println(g.printPath(END));
}
} catch (Exception e) {
}
除了 g.printPath(END) 行之外,我对这段代码没有任何问题。我收到的错误是“此处不允许使用 void 类型”。我完全明白这意味着什么。发生这种情况是因为 printPath 方法无效。它看起来像这样:
public void printPath(String end) {
if (!graph.containsKey(end)) {
System.err.printf("End vertex is not contained within graph \"%s\"\n", end);
return;
}
graph.get(end).printPath();
System.out.println();
}
由于我需要访问它将打印的变量,因此我尝试修改它以具有可以写入文本文件的返回类型。我想到的是:
public String printPath(String end) {
if (!graph.containsKey(end)) {
System.err.printf("End vertex is not contained within graph \"%s\"\n", end);
return null;
}
graph.get(end).printPath();
System.out.println();
return graph.get(end).printPath();
}
这又出现错误,因为该方法是字符串类型,但 graph.get(end).printPath() 为 void(get 方法也是 void)。我尝试返回其他变量,例如 graph 和 graph.get(end),但它们不返回图中的实际变量。我知道 graph.get(end).printPath() 打印出我想要的正确值。我只是在努力寻找一种存储它们的方法。有没有一种简单的方法可以将其写入我忽略的文本文件,而不必返回并编辑我的所有方法以使它们不无效?谢谢!
最佳答案
有一种方法可以通过重定向来实现System.out.print
:
public String printPath(Graph graph, String end) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(bos);
//set output stream to bos to capture output
System.setOut(printStream);
graph.get(end).printPath(); //your output
System.out.println();
//reset output stream to file descriptor
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
return bos.toString();
}
- 将
System.out
重定向到ByteArrayOutputStream
, - 开始打印
- 将
System.out
重置为FileDescriptor
最后,真的不建议这样做,这是肮脏的代码,重要的是它不是线程安全的,而且很令人困惑。有一个关于如何处理这个问题的建议:
- 创建一个方法来格式化
graph.get(end)
并返回正确的String
类型路径
关于java - 从 void 方法写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274761/