如何让BufferedWriter写入文本文件?

时间:2017-03-02 00:35:42

标签: java bufferedreader filereader filewriter bufferedwriter

我试图用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个不同的ArrayLists。

然后,如果您选择了要添加约会(先前已定义变量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()。那么为什么当我检查它应该保存到的文件时,它仍然显示为空白?这是我第一次处理文件保存问题,所以我不确定为什么它不能按原样运行。

编辑:如果选择该选项打开现有文件而不是创建新文件,则文件现在只会读取

1 个答案:

答案 0 :(得分:0)

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

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();