为什么这段代码会导致Java写入文件中的数据?

时间:2014-09-28 19:11:17

标签: java bufferedreader bufferedwriter

我不确定为什么下面的代码会导致Java每次都覆盖我文件中已有的数据,而我想要它实际上是在新行上写下每个新数据。我已经包含了相关的代码片段(我知道你可能认为变量中存在错误,但是没有,程序运行正常)。有人可以帮助我理解导致这种情况的原因,是我使用文件编写器的方式吗?

String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.

String Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
    try{
        //Create writer to write to files.
        File file = new File(DirToWriteFile);
        Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));         
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader("VirtualATM.txt");
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String CurrentData = "";
        while((bufferedReader.readLine()) != null) {
                line = CurrentData;
                bw.write(CurrentData);
                ((BufferedWriter) bw).newLine();
        }
        bw.write(Details);
        System.out.println("Account created!");

        System.out.println(name + " Your card number is: " + CardNo);
        //  close the reader.
        bufferedReader.close();
        //Close the writer.
        bw.close();

1 个答案:

答案 0 :(得分:5)

使用另一个FileOutputStream构造函数,即将布尔追加参数作为第二个参数的构造函数。传递true,因为这将告诉Java将文本附加到现有文件而不是覆盖它。

即改变这个:

    File file = new File(DirToWriteFile);
    Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));         

到此:

    File file = new File(DirToWriteFile);
    FileOutputStream fos = new FileOutputStream(file, true); // **note second param?**
    Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));