Search code examples
javaswingjfilechooserfilefilter

How can I get the directory in JFileChooser?


I want to get the full path and the file name. I tried

package looks;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Test {

    public static void main (String[] args) {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "CSV files", "csv");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(chooser);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("directory and file : " +
                                chooser.getSelectedFile().getName() + 
                                chooser.getAbsolutePath().getName());
        }
    }
}

My ultimate goal is to get the String like this C:\\Users..\\Test\\myfile.csv so that I could use it in code.


Solution

  • Try this:

    public static void main (String[] args) {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "CSV files", "csv");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(chooser);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            System.out.println(file.getAbsolutePath());
        }
    }