如何在JFileChooser中获取目录?

时间:2013-11-21 18:29:06

标签: java swing jfilechooser filefilter

我想获取完整路径和文件名。 我试过了

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());
        }
    }
}

我的最终目标是获取类似于C:\\Users..\\Test\\myfile.csv的字符串,以便我可以在代码中使用它。

1 个答案:

答案 0 :(得分:3)

试试这个:

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());
    }
}