在Java中重新访问文件后保留保存的数据

时间:2018-11-02 11:25:49

标签: java file append

写入的数据未追加,正在删除先前的文件数据。我的要求是将写入的内容添加到给定的文件中。

package com.search.book.dictionary;

import java.io.*;
import java.util.Scanner;

public class Dictionary1 {

    public static void main(String[] args) throws IOException {

        try {
            FileReader fr = new FileReader("D:\\dictionary.csv");
            FileWriter fw = new FileWriter("D:\\testout.txt");
            BufferedReader br = new BufferedReader(fr);
            BufferedWriter buffer = new BufferedWriter(fw);
            Scanner scan = new Scanner(System.in);
            String letter = scan.next();
            String line;
            Boolean valid = false;
            File file = new File("D:\\testout.txt");

            while ((line = br.readLine()) != null) {

                System.out.println("not found");
                fw = new FileWriter(file.getAbsoluteFile(), true);
                buffer = new BufferedWriter(fw);
                buffer.write(letter);

                if (buffer != null)
                    buffer.close();

                if (fw != null)
                    fw.close();
            }
        }

        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("File not found");
        }
    }
}

0 个答案:

没有答案