【发布时间】:2013-01-07 16:56:00
【问题描述】:
我有一个简单的程序,需要使用FileWriter 和BufferedWriter 将几行字符串写入文件。它已经从文件中读取了(在这种情况下)完全相同的数据,并将其存储在运行时内存中,但它完全拒绝写入它,我不知道为什么。通常我会尝试调试它并查看发生了什么,但我不知道我在寻找什么。
这是我的代码:
public void close () {
FileWriter output = null;
BufferedWriter fileOut = null;
// I use the exact same method to read from file so this should work
// this.prajituri :: ArrayList
// toString is @Override
try {
output = new FileWriter(this.fileName);
fileOut = new BufferedWriter(output);
for (int i = 0; i < this.prajituri.size(); i++) {
fileOut.write(prajituri.get(i).toString());
System.out.println(prajituri.get(i).toString());
fileOut.newLine();
}
} catch (IOException ioe) {
System.out.println("Output error: " + ioe);
} finally {
if (fileOut != null)
fileOut = null;
if (output != null)
output = null;
}
}
以防万一,这是我的 toString:
@Override
public String toString () {
return this.name + ";" + this.weight + ";" + this.price;
}
每次我尝试写入文件时,它都会给我一个空文件。我是不是做错了什么?
我检查了,this.prajituri 实际上很好(拥有它应该拥有的所有数据)
我使用System.out.println(prajituri.get(i).toString()) 来检查它应该 写什么,这也可以。然而它什么也没写。
【问题讨论】:
-
if (fileOut != null) fileOut.close;而不是fileOut = null;