I'm trying to write in a file whatever the user has written. The file creates and all but the program fails to write whatever the user wrote from the program, to the file (The program is like notepad). It wont enter the while loop because the String line is null even if I write something in my program.
It seems it's returning null when I print the "line" String after using br.readLine().
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
Full code:
try {
path = fileChooser.getSelectedFile().getAbsolutePath().replace('\\', '/')
+ "/";
File file = new File(path + File.separator +
JOptionPane.showInputDialog(null, "File name", "File") + ".txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
bw.flush();
bw.close();
textArea.append(path);
} catch(IOException e1) {
e1.printStackTrace();
}
file.createNewFile();
. . .
BufferedReader br = new BufferedReader(new FileReader(file));
The reader works from an empty file that just has been created. Of course br.readLine()
will return null immediately since the file is empty.
Instead of the while loop, I would simply write:
bw.write(textArea.getText());