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 ofWriter.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.