【发布时间】:2014-09-05 16:42:59
【问题描述】:
我只是想在我的 *.txt 文件中添加一个新的文本行,但什么也没有发生。该文件包含一个 .war,因此我使用 ClassLoader 来访问该文件。此外,我的 Eclipse IDE 和文件内容都使用 UTF-8 编码。
我用这些来获得灵感:
How to add a new line of text to an existing file in Java?
Java BufferedWriter object with utf-8
现在我的代码主要是基于上一篇的,大概是这样的:
public class test {
public static void main(String[] args){
URL url = Thread.currentThread().getContextClassLoader().getResource("MilestoneExport.txt");
File file = new File(url.getFile());
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我已确认该文件确实已找到,并且可以正常读取。我已经能够通过使用BufferedReader 将它的全部内容输出到控制台。文件的路径也是正确的,但绝对没有文本添加到文件中。我确保每次运行程序时都进行了刷新和更新。
另外,我尝试创建一个名为foo.txt 的简单空文件,它与test.java 位于同一目录中。我在 BufferedWriter API 提供的 main 方法中添加了以下代码,位于 http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
PrintWriter out2 = new PrintWriter(
new BufferedWriter(new FileWriter("foo.txt")));
out2.println("new Line");
out2.close();
我在这里缺少什么?为什么没有错误消息,也没有任何响应或反馈?
以下所有内容仅是关于我尝试过的内容的附加信息。在任何情况下都没有反馈:
- 不是这个:Why is BufferedWriter not writing to file?
- 不是这个:why is bufferedwriter not writing in the file?
- 不是这个:Unable to write to file using BufferedWriter
- 又一个“记得关闭/刷新”:Java : Problems accessing and writing to file
- 在
try块之外定义BufferedWriter 没有区别,但我还是尝试了,因为How to write detail into file using BufferedWriter and FileWriter in Java?
此外,此答案中的此代码也没有执行任何操作...
try {
BufferedWriter output = new BufferedWriter(new FileWriter(new File("house.txt")));
output.write("text");
output.close();
}
catch (IOException e) {
e.printStackTrace();
}
最后但并非最不重要的一点是,我怀疑这可能与我的 Web 应用程序的打包有关,以及源文件夹和目标文件夹之间的差异。所以我将代码复制到一个全新的干净项目中,但它仍然什么也没做......
编辑:
这段代码:
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getName());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.setLastModified(new GregorianCalendar().getTimeInMillis()));
提供这些输出:
- 是的
- D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
- D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
- 里程碑导出.txt
- 假
- 是的
- 是的
我是否完全误解了 java 的 File-objects 的使用,以及它与 FileWriters 的使用?该文件显然是 100% 确认正确的文件。
【问题讨论】:
标签: java file-io append bufferedwriter