How do I make JFileChooser open in the current dir

2019-08-10 21:40发布

问题:

I do not want to specify a directory. I just want it to automatically "know" and open in the directory the user is working in. How do I do this?

回答1:

This examples defaults to the user.dir on first showing. It then retains the instance of the chooser to automatically track the last load or save location, as suggested by MadProgrammer.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;

public class ChooserInCurrentDir {

    // the GUI as seen by the user (without frame)
    JPanel gui = new JPanel(new BorderLayout());
    JFileChooser fileChooser;
    private JTextArea output = new JTextArea(10, 40);

    ChooserInCurrentDir() {
        initComponents();
    }

    public final void initComponents() {
        gui.setBorder(new EmptyBorder(2, 3, 2, 3));

        String userDirLocation = System.getProperty("user.dir");
        File userDir = new File(userDirLocation);
        // default to user directory
        fileChooser = new JFileChooser(userDir);

        Action open = new AbstractAction("Open") {

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showOpenDialog(gui);
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        File f = fileChooser.getSelectedFile();
                        FileReader fr = new FileReader(f);
                        output.read(fr, f);
                        fr.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };

        Action save = new AbstractAction("Save") {

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showSaveDialog(gui);
                throw new UnsupportedOperationException("Not supported yet.");
            }
        };

        JToolBar tb = new JToolBar();
        gui.add(tb, BorderLayout.PAGE_START);
        tb.add(open);
        tb.add(save);

        output.setWrapStyleWord(true);
        output.setLineWrap(true);

        gui.add(new JScrollPane(
                output,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    }

    public final JComponent getGui() {
        return gui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                ChooserInCurrentDir cicd = new ChooserInCurrentDir();
                JFrame f = new JFrame("Chooser In Current Dir");
                f.add(cicd.getGui());
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}


回答2:

Basically, you can't. You need to tell it.

When constructed with a null currentDirectory (such as the default constructor), it will use FileSystemView#getDefaultDirectory.

You could create a single instance of JFileChooser for each base task (one for saving, one for opening for example) and simply maintain that instance, which will "remember" the last directory that it was using, you'd still need to seed it with a starting directory though

Another choice would be to construct some kind of library call that could load and save the last directory the user used based on some unique key. This means you could simply do something like...

File toFile = MyAwesomeLibrary.getSaveFile(APPLICATION_DOCUMENT_SAVE_KEY);

Which would load the last known directory for the supplied key and show the JFileChooser configured with that value and would be capable of returning the selected File or null if the user canceled the operation...for example...



回答3:

If you want to set the directory they were in at the previous opening of the file chooser you need to set the current directory.

//This will set the directory to the directory they previously chose a file from.
fileChooser.setCurrentDirectory(fileChooser.getCurrentDirectory());

Im not sure if this is what you're looking for, But when they select a file then go to select another file, it will maintain the directory they were in from the previous selection.



回答4:

If you want your application to look for the user's working directory, you can try this:

String curDir = System.getProperty("user.dir");