简体   繁体   English

JTextPane从文本文件读取

[英]JTextPane read from text file

I have a .txt file which has 3 lines 我有一个.txt文件,其中有3行

My GUI code is 我的GUI代码是

txtpnEmergencyAmbulanceAnd = new JTextPane();
     try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = new FileReader(fileNumbers);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            while((lineNumbers = bufferedReader.readLine()) != null) {
    txtpnEmergencyAmbulanceAnd.setText(lineNumbers);
        }
            // Always close files.
            bufferedReader.close();            
        }

     catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileNumbers + "'");                
        }
     catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileNumbers + "'");      
     }

However what prints into my GUI is only the last line. 但是,打印到我的GUI中的只是最后一行。 I'm trying to print out all three lines I have also included this as a global 我正在尝试打印出所有这三行内容,并将其作为全局

String fileNumbers = "numbers.txt";

String lineNumbers = "";

setText does exactly, sets the components text to the value you pass it, discarding any content it previously had. setText确实会执行此操作,将组件文本设置为您传递给它的值,并丢弃以前拥有的任何内容。

Instead try using JTextPane#read(Reader, Object) 而是尝试使用JTextPane#read(Reader, Object)

FYI: You might want to take a closer look at The try-with-resources Statement in order to manage your resources better 仅供参考:为了更好地管理资源,您可能需要仔细研究“资源尝试”语句

Yes, because you overwrite the contents of your JTextPane on every run. 是的,因为您每次运行都会覆盖JTextPane的内容。

Quick and dirty solution: 快速而肮脏的解决方案:

txtpnEmergencyAmbulanceAnd.setText(txtpnEmergencyAmbulanceAnd.getText() + lineNumbers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM