Suggestion on how to read large file in jtextarea

I want to read a large file like 10-15k lines into jtextarea. In addition, I also have to add each line to the list and highlight some specific lines in the jtextarea.

What I have tried so far, I am transferring the file to FileReader to BufferedReader. Inside my SwingWorker, in the doBackground method, I call:

 while ((line = br.readLine()) != null) {
      textArea.append(line);
      textArea.append(System.getProperty("line.separator"));
      list.add(line);
      highlightLine(lineNumber);
 }

      

When I run the program and I select the file and open the read process, it instantly loads up to 700 lines, then the program slows down and loads like 10 lines per second.

Another idea I have is to read the entire file using the JTextComponent read method (which seems to be setText faster than adding each line), and then, read the whole file again, or iterate over each line in jtextarea and add that line to list and also highlight, which, I think, is not very effective. What are you suggesting to me?

+3


source to share


3 answers


I want to read a large file like 10-15k lines into jtextarea

Use a read(...)

class method JTextArea

to read the entire file directly into the text area.

I also need to add each line to the list

Why do you need two copies of the text? If you want a string of data, you can get the text from the text area:

int start = textArea.getLineStartOffset(...);
int end = textArea.getLineEndOffset(...);
String text = textArea.getDocument().getText(...);

      



to highlight some specific lines

Use a marker to highlight lines after they have loaded into the text area.

Highlighter highlighter = textArea.getHighlighter();
highlighter.addHighlight(...);

      

Again you can get the line offsets using the code above.

+4


source


Use the Document interface. it is the model that contains the view component data JTextArea

. You can get it from JTextArea

using getDocument

or you can use one of the classes that have already been implemented Document

: AbstractDocument, DefaultStyledDocument, HTMLDocument, PlainDocument . Then add Document

Document

to JTextArea

with setDocument

.



You can use insertString(int offset, String str, AttributeSet a)

to add content to Document

. It also supports multiple listeners, and you might consider using it render(Runnable r)

to style your document.

+1


source


I have not tried this, but I would suggest putting the entire content of the file into a String and then using the setText (String text) method to set the JTextArea text right away.

0


source







All Articles