Search code examples
javaswingoopfile-iojtextpane

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 = "";

Solution

  • 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