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

1.3k views Asked by At

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

2

There are 2 answers

0
Pablo Lozano On

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.

0
Benjamin On

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