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

后端 未结 2 678
庸人自扰
庸人自扰 2020-12-21 11:34

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

2条回答
  •  生来不讨喜
    2020-12-21 12:08

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

提交回复
热议问题