-1

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.

enter image description here

It seems it's returning null when I print the "line" String after using br.readLine().

enter image description here

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();
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
vincentes
  • 45
  • 1
  • 1
  • 7
  • There is no need to use BufferedReader and other such things; Java 8 has much better support for file IO. I am guessing you are using an outdated tutorial, try Googgling for more recent ways of IO. Things will work much better for you. – CaffeineToCode Jan 10 '15 at 03:41
  • See also `JTextComponent` [`read(Reader, Object)`](https://docs.oracle.com/javase/8/docs/api/javax/swing/text/JTextComponent.html#read-java.io.Reader-java.lang.Object-) & [`write(Writer)`](https://docs.oracle.com/javase/8/docs/api/javax/swing/text/JTextComponent.html#write-java.io.Writer-).. – Andrew Thompson Jan 10 '15 at 07:29

1 Answers1

2
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());
David Frank
  • 5,918
  • 8
  • 28
  • 43
  • With this code if i write "hello (new line) bye " It prints "hellobye" in 1 line instead of "hello" and "bye" separated by a new line. – vincentes Jan 10 '15 at 19:38
  • @Vincent You are probably using Windows. In this case, see this question: http://stackoverflow.com/questions/9199216/strings-written-to-file-do-not-preserve-line-breaks. While JTextArea uses \n as line breaks, Windows requires \r\n. – David Frank Jan 10 '15 at 20:42