读取文本文件和将内容转储到JTextArea的最有效方法 [英] Most efficient way to read text file and dump content into JTextArea
问题描述
我很好奇读取文本文件的最有效方法是什么(不要担心大小,它相当小,所以 java.io
很好)然后将其内容转储到 JTextArea
中以供显示。
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.
例如。我可以以某种方式使用单个字符串中的整个文件,然后使用 JTextArea.setText
来显示它,或者我应该逐行读取或字节数组并将它们填充到StringBuffer中然后将文本区域设置为?
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?
谢谢
推荐答案
你可以使用 JTextComponent.read(Reader,Object)
并传递 FileReader
。只需这样做:
You can use JTextComponent.read(Reader, Object)
and pass it a FileReader
. Just do this:
Java 7 - 尝试资源块
try (FileReader reader = new FileReader("myfile.txt")) {
textArea.read(reader, null);
}
Java 6 - try-finally block
Java 6 -- try-finally block
FileReader reader = null;
try {
reader = new FileReader("myfile.txt");
textArea.read(reader, null);
} finally {
if (reader != null) {
reader.close();
}
}
这篇关于读取文本文件和将内容转储到JTextArea的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!