如何让 BufferedWriter 写入文本文件?

How to get the BufferedWriter to write to a text file?

我正在尝试在 Java 中创建一个约会簿程序,但是 BufferedWriter 似乎没有写入文件。

此代码全部在 try { } catch (FileNotFoundException) { } catch (IOException) { } 块中

FileWriter writer = new FileWriter("Appointments" + name + ".txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(writer);

if (open == 'o') {
    FileReader reader = new FileReader("Appointments" + name + ".txt");
    BufferedReader bufferedReader = new BufferedReader(reader);
    while ((line = bufferedReader.readLine()) != null) {
        if (line.indexOf("one-time") == line.length() - 8) {
            OneTime o = fromStringOneTime(line);
            oneTimes.add(o);
        }
        if (line.indexOf("daily") == line.length() - 5) {
            Daily d = fromStringDaily(line);
            dailys.add(d);
        }
        if (line.indexOf("monthly") == line.length() - 7) {
            Monthly m = fromStringMonthly(line);
            monthlys.add(m);
        }
    }
}

while 循环只是将文件中当前的所有值初始化为 3 个不同的 ArrayList。

然后我有一段代码可以在您选择要添加约会后创建新对象(变量 descdate 已预先定义):

System.out.print("Enter if this is a (o)ne-time, (d)aily, or (m)onthly appointment: ");
freq = scanner.next().charAt(0);
if (freq == 'o') {
    OneTime o = new OneTime(desc, date.getDate());
    oneTimes.add(o);
    totalCount++;
    bufferedWriter.write(o.toString());
    bufferedWriter.newLine();
    valid = true;
} else if (freq == 'd') {
    Daily o = new Daily(desc, date.getDate());
    dailys.add(o);
    totalCount++;
    bufferedWriter.write(o.toString());
    bufferedWriter.newLine();
    valid = true;
} else if (freq == 'm') {
    Monthly o = new Monthly(desc, date.getDate());
    monthlys.add(o);
    totalCount++;
    bufferedWriter.write(o.toString());
    bufferedWriter.newLine();
    valid = true;
}

在 try 块的末尾,我有行 reader.close()writer.close()。那么为什么当我检查它应该保存到的文件时,它仍然显示为空白?这是我第一次处理文件保存,所以我不确定为什么它没有按应有的方式工作。

编辑:现在只有在选择了打开现有文件而不是创建新文件的选项时才会读取文件

是的,大多数操作系统不允许读取和写入同一个文件。因此,您可以通过使用一些临时文件名写入文件并在程序结束时将其重命名为原始文件来解决此问题

try {
   FileWriter writer = new FileWriter("Appointments" + name + "1.txt", true);
   FileReader reader = new FileReader("Appointments" + name + ".txt");
   BufferedReader bufferedReader= new BufferedReader(reader);
   BufferedWriter bufferedWriter = new BufferedWriter(writer);
   .......
} catch () {
   ......
} finally {
   bufferedReader.close();
   bufferedWriter.flush();
   bufferedWriter.close();
}

// Rename the file and delete temp file
File srcFile = new File("Appointments" + name + "1.txt");
File targerFile = new File("Appointments" + name + ".txt");
srcFile.renameTo(targetFile);
srcFile.delete();