Java:为什么我的文件不能写入文件?
问题描述:
我想从我的Java程序写一个文件,但没有任何反应。我没有得到任何例外或错误,只是默默地失败。Java:为什么我的文件不能写入文件?
try {
File outputFile = new File(args[args.length - 1]);
outputFile.delete();
outputFile.createNewFile();
PrintStream output = new PrintStream(new FileOutputStream(outputFile));
TreePrinter.printNewickFormat(tree, output);
} catch (IOException e) {
e.printStackTrace();
return;
}
这里是TreePrinter
功能:
public static void printNewickFormat(PhylogenyTree node, PrintStream stream) {
if (node.getChildren().size() > 0) {
stream.print("(");
int i = 1;
for (PhylogenyTree pt : node.getChildren()) {
printNewickFormat(pt, stream);
if (i != node.getChildren().size()) {
stream.print(",");
}
i++;
}
stream.print(")");
}
stream.format("[%s]%s", node.getAnimal().getLatinName(), node.getAnimal().getName());
}
我在做什么错?
答
关闭和/或刷新你的输出流:
TreePrinter.printNewickFormat(tree, output);
output.close(); // <-- this is the missing part
} catch (IOException e) {
此外,还可通过delete()
/createNewFile()
是不必要的 - 你的输出流将创建或覆盖现有文件。
+0
在这种情况下,您的节点必须为空 - 没有任何内容写入文件。您可以通过在关闭之前打印某些东西来测试是否属于这种情况(或者您有其他问题),例如, 'output.println( “测试”);' – ChssPly76 2009-11-20 03:15:51
答
刷新PrintStream。
该代码保证至少会创建一个(可能为空)文件或抛出一些异常。 – 2009-11-20 09:32:02