0

Hey I need to read a text file content and store it (for example inside a string). The problem is, that I don't want to read a certain file, like here:

btnOpen.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
                {
                    try
                    {
                        FileReader reader = new FileReader( "TextAreaLoad.txt" );
                        BufferedReader br = new BufferedReader(reader);
                        edit.read( br, null );
                        br.close();
                        edit.requestFocus();
                    }
                    catch(Exception e2) { System.out.println(e2); }
                }
}

I would like to get contains of a file, choosed with fileChooser, like:

btnOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //Handle open button action.
                if (e.getSource() == btnOpen) {
                    int returnVal = fc.showOpenDialog(Main.this);

                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();

                    } 
                    else {

                    }
               } 
            }
});

Question is: how?

user3235376
  • 87
  • 1
  • 2
  • 10

1 Answers1

0

Now that you have the File, you can create a FileReader from it and use it just like you do in your first example. FileReader has a constructor that takes a File as a parameter. But I would move the call to the close method into a finally block.

David Conrad
  • 15,432
  • 2
  • 42
  • 54