Search code examples
javaswingfile-iojava.util.scannerjtextarea

Add a line at a time to a String


I have this program that lets you open a file and it reads it in to a JTextArea all at once using the following code:

 try{
    String fileContents = new Scanner(new File(fileName)).useDelimiter("\\Z").next();
  }catch(FileNotFoundException ex){
    ex.printStackTrace();
  }

  myTextArea.setText(fileContents);

and this works. But my question is how can I read this into my fileContents string and still have it add in the line breaks every time I get a new-line character?

Here is what I have, but this puts it all in one line in my textArea:

 try{
Scanner contentsTextFile = new Scanner(new File(fileName));
while(contentsTextFile.hasNext()){
    fileContents = contentsTextFile.useDelimiter("\r\n|\n").nextLine(); 
    }

}catch(FileNotFoundException ex){
    ex.printStackTrace();
}

   myTextArea.setText(fileContents);

What I would like to see is this line of text get a new line using a delimiter that only reads one line at a time instead of the entire file.

Can someone help?


Solution

  • You can read a file line-by-line using a BufferedReader and use the append() method of JTextArea for each line read. For convenience, wrap the JTextArea in a suitably sized JScrollPane, as shown here. If you anticipate any latency, use a SwingWorker to read in the background, and call append() in process().

    BufferedReader in = new BufferedReader(new FileReader(fileName));
    String s;
    while ((s = in.readLine()) != null) {
        myTextArea.append(s + "\n");
    }