Most efficient way to read text file and dump content into JTextArea

懵懂的女人 提交于 2019-11-30 09:37:44

问题


I am curious what the most efficient way is to read a text file (do not worry about size, it is reasonably small so java.io is fine) and then dump its contents into a JTextArea for display.

E.g. can I somehow consume the entire file in a single string and then use JTextArea.setText to display it or should I read line by line or byte arrays and populate them into a StringBuffer and then set the text area to that?

Thanks


回答1:


You can use JTextComponent.read(Reader, Object) and pass it a FileReader. Just do this:

Java 7 -- try-resource block

try (FileReader reader = new FileReader("myfile.txt")) {
    textArea.read(reader, null);
}

Java 6 -- try-finally block

FileReader reader = null;
try {
    reader = new FileReader("myfile.txt");
    textArea.read(reader, null);
} finally {
    if (reader != null) {
        reader.close();
    }
}



回答2:


Rather than reading the full contents of the file, you could allow the JTextArea component to use a Reader to read the file's InputStream:

FileReader fr = new FileReader(fileName);
textArea.read(fr, null);


来源:https://stackoverflow.com/questions/13186818/most-efficient-way-to-read-text-file-and-dump-content-into-jtextarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!