2

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?

mKorbel
  • 108,320
  • 17
  • 126
  • 296
kandroidj
  • 12,901
  • 5
  • 56
  • 69

2 Answers2

3

The easiest way is to use JTextComponent.read(Reader,Object) which:

Initializes from a stream. This creates a model of the type appropriate for the component and initializes the model from the stream. By default this will load the model as plain text. Previous contents of the model are discarded.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
3

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");
}
Community
  • 1
  • 1
trashgod
  • 196,350
  • 25
  • 213
  • 918
  • yeah this is what i decided i would do. I get the file contents using the `FileReader` and `BufferedReader` then i append them one at a time to the `JTextArea` using `myTextArea.append(contents);` – kandroidj May 16 '13 at 19:35
  • 1
    +1 but JTextComponent.read/write accepting separators in file (both directions I/O) – mKorbel May 16 '13 at 20:02
  • 2
    @mKorbel: Agree for undivided operation on `Document`. Anything but `Scanner`! :-) – trashgod May 16 '13 at 20:22