Search code examples
javaswingtextiojtextarea

Java IO: Reading text files as they are seen


I have a text file which contains something like this:

Hello, my name is Joe

What is your name?
My name is Jack.

That is good for you.

The only problem is that I have to load it into a JTextArea with the append method to display the text in a JScrollPane like so:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);

But when I read the file into the text area, the text area displays something like this:

Hello, my name is JoeWhat is your name?My name is Jack.That is good for you.

The BufferedReader never reads in newlines (\n) into the JTextArea. How could I make the reader add the spaces and blank lines as they appear in the file? If anyone can help I would appreciate it. Thanks!


Solution

  • All JTextComponents have the ability to read in text files and write to text files while fully respecting the newline character for the current operating system, and it is often advantageous to use this. In your case, you would use the JTextArea's read(...) method to read in the file while fully understanding the file system's native new-line character. Something like so:

    BufferedReader br = new BufferedReader(new FileReader(file));
    textArea.read(br, null);
    

    Or for a more complete example:

    import java.io.*;
    import javax.swing.*;
    
    public class TextIntoTextArea {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    
       private static void createAndShowGui() {
          JFileChooser fileChooser = new JFileChooser();
          int response = fileChooser.showOpenDialog(null);
          if (response == JFileChooser.APPROVE_OPTION) {
             File file = fileChooser.getSelectedFile();
             BufferedReader br = null;
             try {
                br = new BufferedReader(new FileReader(file));
                final JTextArea textArea = new JTextArea(20, 40);
    
                textArea.read(br, null); // here we read in the text file
    
                JOptionPane.showMessageDialog(null, new JScrollPane(textArea));
             } catch (FileNotFoundException e) {
                e.printStackTrace();
             } catch (IOException e) {
                e.printStackTrace();
             } finally {
                if (br != null) {
                   try {
                      br.close();
                   } catch (IOException e) {
                   }
                }
             }
          }
       }
    }