try {
File file = new File("sample.txt");
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
fw.close();
} catch(IOException exp) {
exp.printStackTrace();
}
我无法向文件追加或写入任何内容。
但我可以从文件中读取内容。
我的代码有什么问题吗?
最佳答案
听起来您可能正在写入文件 - 但不是您期望的文件。如果没有抛出异常(吞下异常,将其写入标准输出很少是正确的方法),那么该文件将存在于某处。
它将位于运行代码的任何目录中 - 这很可能不与包含您正在阅读的 sample.txt
文件的目录相同。我建议您探索文件系统,并检查 Eclipse 中的运行配置以查看应用程序的工作目录。
顺便说一句,您应该在 finally
block 中关闭编写器,这样即使出现异常也会关闭它,如下所示:
File file = new File("sample.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.append('d');
fw.write(100);
} catch(IOException) {
// Ideally do something to indicate the failure to the caller
// - do you need to catch this at all?
e.printStackTrace();
} finally {
// From Guava
Closeables.closeQuietly(fw);
}
显然你可以在没有 Guava 的情况下做到这一点但它会让事情变得简单得多 - 不仅仅是在这里。如果您使用的是 Java 7,则可以使用 try-with-resources statement 使其更加简单.
关于java - 如何将内容写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321593/