我有一个赋值,我有一个构造函数和两个方法。构造函数打开文件,如果文件不存在,则创建一个文件。这些方法只是在文件中添加一个新行,并从文件中删除一个特定的行。我有这个:
public openFile(String fileName) {
File f = new File(filename);
BufferedReader b = new BufferedReader(new FileReader(f));
String line;
if (f.exists()) {
while ((line = b.readLine()) != null) {
if (b.readLine().contains(COMMA)) {
String[] tokens = line.split(COMMA); // parse information on line
User u = new User(tokens[0], tokens[1]); // Creates new user
} else {
f.createNewFile();
}
b.close();
}
}
}
我的其他方法是:
public add(String[] args) {
FileWriter fileWriter;
BufferedWriter bufferedWriter;
String message = args[1] + COMMA + args[2] + "\n";
try {
fileWriter = new FileWriter(TEST_CSV, true); // Test_CSV is name of the file I have to write to.
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(message);
bufferedWriter.close();
} catch (IOException e) {
//Do nothing
}
但它根本不起作用。我怎么能改变它,以便它可以添加文件而不删除它并每次都创建一个新文件。
答案 0 :(得分:0)
我认为您的f.createNewFile();
位置错误,每次从文件中读取一行时都会执行,请尝试以下操作:
public openFile(String fileName) {
File f = new File(filename);
BufferedReader b = new BufferedReader(new FileReader(f));
String line;
if (f.exists()) {
while ((line = b.readLine()) != null) {
if (b.readLine().contains(COMMA)) {
String[] tokens = line.split(COMMA); // parse information on line
User u = new User(tokens[0], tokens[1]); // Creates new user
}
}
} else {
f.createNewFile();
}
b.close();
}
另外,你在每一行之后都关闭了缓冲的阅读器,所以我移动了b.close();