简体   繁体   中英

JTextPane read from text file

I have a .txt file which has 3 lines

My GUI code is

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. 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.

Instead try using 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.

Quick and dirty solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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