Easily Open a File in Java

Say you wanted to open a file in Java, either for reading or writing. But it’s not clear how to do it, and whether you need a GUI, and blah blah blah, wouldn’t it be nice to just find a minimal example? ¬†Well then, here you go.

import javax.swing.*;   // for JFileChooser
import java.io.*;       // for File
import java.util.*;     // for Scanner (if you want to read it in)

class FileOpener {

    public static void main(String[] args) {
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            // it's in your hands now...
        }
    }
}

Solid. Now say you want to read from the file:

            try {
                // read in the file
                Scanner s = new Scanner(f);
                String str = s.nextLine();
                // ...
            } catch(FileNotFoundException e) {
                // Couldn't find the file for some reason
                e.printStackTrace();
            }

Or writing to the file:

            try {
                FileWriter fw = new FileWriter(f);
                fw.write("Hello, World!");
                // ...
            } catch(IOException e) {
                // didn't work
                e.printStackTrace();
            }

Ta-da! Protip: If you’re using this as part of a GUI with a Component “comp” showing your main GUI screen, set “comp” to be the parent of the filechooser dialog by calling fc.showOpenDialog(comp);.

Other protip: if you really want, you can subject yourself to the official tutorial here.