4

I'm trying to show on screen a textfile content using JavaFX textarea. I success doing it with small files, but with big ones everything becomes too slow. File with size 64KB was read in 1 second, and it takes 2 minutes to display it. There is code:

try (FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader)) {
    char[] buf = new char[102400];
    int haveRead;
    while ((haveRead = reader.read(buf)) != -1) {
        buf = Arrays.copyOf(buf, haveRead);
        String str = new String(buf);
        textArea.appendText(str);
        log.trace(str);
    }
} catch (IOException e) {
    log.error("Error while reading file", e);
}

Logging shows that even with multithreading almost all time program waiting for

textArea.appendText(str);

What to do? Is there faster implementation or mine faults in code? or the only way is to do buffer of displaying text, somehow overriding the behavior of textarea slider?

Developer66
  • 732
  • 6
  • 17
Lless
  • 43
  • 4
  • Try to load the text at first to a String and display it at one time... Updating the UI needs lot's of time... So instead of `textArea.appendText(str)` load the text to a String and later say: `textArea.setText(YourString)` – Developer66 Sep 01 '17 at 06:57
  • i'll try, but what if file will be really big, about 2GB? and there can be not only one such file. – Lless Sep 01 '17 at 07:04
  • Hmm, the string is saved in the memory so your `Ram` contains now 2GB more, but in your methode this is the same... Maybe you must access more memory to the Progamm with the java options:https://stackoverflow.com/a/2294280/8087490 – Developer66 Sep 01 '17 at 07:07

1 Answers1

3

Don't use TextArea when you have more than thousand lines of text.

If you want just to display the text simply use a ListView<String>:

But if you need to edit the Text you have to build your own BigTextArea or look for a good library with one. For example RichTextFx:

StyleClassedTextArea bigTextArea = new StyleClassedTextArea();
try (FileReader fileReader = new FileReader(file);
                    BufferedReader reader = new BufferedReader(fileReader)) {
    StringBuilder sb = new StringBuilder();
    while ((haveRead = reader.read(buf)) != -1) {
        sb.append(buf);
    }
    bigTextArea.appendText(sb.toString());
} catch (IOException e) {
    log.error("Error while reading file", e);
}
  • Thank you. ListView is extremely fast, but for my purposes its functionality is too poor. I used RichTextFX before, but i didn't ever think it faster than TextArea. It is. So, with using RichTextFX and only-one-text-appending 50MB file is opening in 5 seconds. Could be better, but for me is fast enough. – Lless Sep 01 '17 at 08:34