简体   繁体   中英

Write words to file.txt using Bufferedwrite and bufferedread in Java

I have a problem with my code. I want to make a simple dictionary which database is stored in a txt file. I want to add new words to the txt file using BufferedWriter but it doesn't work anymore. Even it remove all the data in the txt file while i run the program This is the oode :

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AddWords {

    public void addToDictionary(String _add) {

        String line = null;
        BufferedReader br = null;
        BufferedWriter wr = null;

        int count = 0;    
        try {
            String path = "E:\\Lecture\\Semester 3\\IF321314 OOP\\Week 10\\Pratikum\\Sesi 01\\Kamus\\dictionary.txt";
            br = new BufferedReader(new FileReader(path));
            while ((line = br.readLine()) != null) {

            }
            wr = new BufferedWriter(new FileWriter(path));
            wr.newLine();
            wr.write(_add);
            br.close();
            System.out.println("Words successfully added!");
        } catch (IOException ex) {

        }
    }
}

The parameter "_add" is make in another file that is an input from the user, that is a new word that i want to add to the txt file

I reckon your problem is you think the Reader and the Writer share in some way the position of the file where they are working, but that's not true. You don't need that Reader, and you can use Writer.append instead of Writer.write to add new text at the end of the file without overwriting the previous data.

An off-topic piece of advice: I never use FileWriter because there is no way to define the charset, it always uses the OS default one. I think it's better to use an FileOutputStream wrapped in a OutputStreamWriter, which can define a custom charset.

You can write instread of

        wr = new BufferedWriter(new FileWriter(path));

like this

        wr = new BufferedWriter(new FileWriter(path,true));

This is samll example to append a file.

            //true = append file
            FileWriter fileWritter = new FileWriter(path,true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(data);
            bufferWritter.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM