user3160068
user3160068

Reputation: 1

Using JFileChooser and File handlng

I am having trouble of using JFileChooser to open text files and read it in the console, I try to get source codes from some tutorials but I only got codes for "file handling" and "how to use JFileChooser" and I tried to combine them or something just to work out but I cant seem to do it, I'm really running out of ideas, any help will do.

Upvotes: 0

Views: 78

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208964

If the JFileChooser returns JFileChooser.APPROVE_OPTION, using .getSelectedFile() will return a File object

File file;
JFileChooser chooser = new JFileChooer();
int returnValue = JFileChooser.showOpenDialog(this);
if (returnVal = JFileChooser.APPROVE_OPTION){
    file = chooser.getSelectedFile();
}

If you understand how to you basic I/O, then you should know what to do with that file.

Something fairly simple would just be something like this

try {
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line;
    while ((line = in.readLine()) != null){
        textArea.append(line + "\n");
} catch(IOException ex){
    ex.printStackTrace();
}

  • Another option is to use the JTextComponent#read() method

  • Another option is to use a JEditorPane and just use its setPage() method

    JEditorPane document = new JEditorPane();
    
    File file = fileChooser.getSelectedFile();
    try {
         document.setPage(file.toURI().toURL());
    } catch(Exception e) {
         e.printStackTrace();
    }
    

If you need basic help with I/O, see this tutorial

Upvotes: 2

Related Questions