-4

I want to read text files in Java. How to do? I have JFileChooser. It will approve and then open file. After read it will show in JTextArea. My Code:

ActionListener openButton_Click = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // put code here
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • This question was originally closed as a duplicate of https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java which simply shows how to read a text tile. This question is about reading a file into a JTextArea. Question was reopened and closed with a more appropriate duplicate. – camickr Feb 05 '22 at 15:27

1 Answers1

-2

Use the Scanner class:

int dialogResult = jFileChooser.showOpenDialog(null);
if (dialogResult == jFileChooser.APPROVE_OPTION) { 
    try {
        Scanner sc = new Scanner(jFileChooser.getSelectedFile());
        sc.useDelimiter("\\Z");
        
        jTextArea.setText(sc.next());
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
}

You assign an int to jFileChooser.showOpenDialog(null) to get the result. Then, if it is the OK button that the user pressed, read the file with the scanner.

  • I didn't downvote but I would guess it was downvoted because it doesn't answer the question. The next() method will read a single line from the file not the entire file. – camickr Feb 05 '22 at 15:25
  • @camickr It works for me. It read a multiline file normally – TheWaterWave222 Feb 12 '22 at 19:01
  • Yes, I see now that it would read the entire file. However, it is still not the best solution for the following reasons: 1) you have now introduced parsing of the data as you read the file which adds unnecessary overhead 2) the entire file is contained in a single String which is not good for large files 3) the String then needs to be reparsed to be added to the text area.. Text components have a read(...) method which would be better optimized to read data from a file and load into the text component. – camickr Feb 12 '22 at 19:38