Add a line at a time to a String

2019-07-15 09:17发布

问题:

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?

回答1:

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");
}


回答2:

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.