我对Java很新。我试图添加" List:"到新文本文件的开头,如果它不存在。相反,文本文件为空白,输入下方是一行空格。
File hi = new File("hi.txt");
try{
if(!hi.exists()){
System.out.printf("\nCreating 'hi.txt'.");
hi.createNewFile();
String hello = "List:";
new FileWriter(hi).append(hello);
}
else{
System.out.printf("\nWriting to 'hi.txt'");
}
FileWriter writeHere = new FileWriter(hi, true);
String uling = "hi";
writeHere.append(uling);
writeHere.close();
}
//error catching
catch(IOException e){
System.out.printf("\nError. Check the file 'hi.txt'.");}
答案 0 :(得分:3)
问题在于这一行:
new FileWriter(hi).append(hello);
你没有关闭作家,这意味着:
你应该养成使用try-with-resources获取然后自动关闭writer的习惯,即使发生异常也是如此。
就个人而言,我稍微更改了代码的结构,因此您只需打开一次文件:
File hi = new File("hi.txt");
boolean newFile = !hi.exists();
System.out.printf("%n%s 'hi.txt'.", newFile ? "Creating" : "Writing to");
try (Writer writer = new FileWriter(hi, true)) {
// Note: if you've already got a string, you might as well use write...
if (newFile) {
writer.write("List:");
}
writer.write(uling);
}
catch(IOException e) {
System.out.printf("\nError. Check the file 'hi.txt'.");
}
答案 1 :(得分:1)
将true作为第二个参数传递给FileWriter以打开“追加”模式(在您创建的第一个FileWriter中)。
此外,您应该创建变量FileWriter
,并在附加“List:”后关闭它,因为您将保留该变量的范围。
所以,我会按如下方式编辑代码:
File hi = new File("hi.txt");
try {
if (!hi.exists()) {
System.out.printf("\nCreating 'hi.txt'.");
hi.createNewFile();
String hello = "List:";
FileWriter writer = new FileWriter(hi, true);
writer.append(hello);
writer.close();
} else {
System.out.printf("\nWriting to 'hi.txt'");
}
FileWriter writeHere = new FileWriter(hi, true);
String uling = "hi";
writeHere.append(uling);
writeHere.close();
}
//error catching
catch (IOException e) {
System.out.printf("\nError. Check the file 'hi.txt'.");
}
注意: 第7-9行的修改 。
http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
答案 2 :(得分:0)
不要忘记关闭作家是非常重要的。好吧,如果你不关闭它,它将不会被写入。
writer.close()。