如何让JFileChooser将文件夹视为目录?

时间:2015-12-15 22:56:08

标签: java swing file-io jfilechooser

我正在尝试使用JFileChooser

选择文件夹中的所有文件
   .setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

但这不允许我选择它只允许我打开它的文件夹。那么我怎么能够用JFileChooser选择一个文件夹然后输入所选文件夹中的所有文件,而不必单独选择每个文件,因为将来文件夹中可能会有很多文件。我的整个代码看起来像这样

  public class PicTest 
  {
   public static void main(String args[])
   {
    File inFile,dir;
    File[] list;
    Image pic[] = new Image[50];
    JFileChooser choose = new JFileChooser();
    choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int status = choose.showOpenDialog(null);
    if(status == JFileChooser.APPROVE_OPTION)
    {
        dir = choose.getCurrentDirectory();
        try
        {
            inFile = new File(choose.getSelectedFile().getAbsolutePath());
            list = dir.listFiles();
            for(int i=0; i < pic.length-1; i++)
            {
                BufferedImage buff = ImageIO.read(inFile);
                pic[i] = buff;
            }
        }
        catch(IOException e) 
        {
            System.out.println("Error");
        }
    }
  }
}                            

1 个答案:

答案 0 :(得分:1)

从您的代码中,您似乎不需要。只需允许用户选择您要处理的目录,并使用File#listFiles获取其内容

然后,您将遍历此列表并读取每个文件,例如..

Image pic[] = null;
JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int status = choose.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
    File dir = choose.getCurrentDirectory();
    if (dir.exists()) {
        File[] list = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                String name = pathname.getName().toLowerCase();
                return name.endsWith(".png")
                        || name.endsWith(".jpg")
                        || name.endsWith(".jpeg")
                        || name.endsWith(".bmp")
                        || name.endsWith(".gif");
            }
        });
        try {
            // Only now do you know the length of the array
            pic = new Image[list.length];
            for (int i = 0; i < pic.length; i++) {
                BufferedImage buff = ImageIO.read(list[i]);
                pic[i] = buff;
            }
        } catch (IOException e) {
            System.out.println("Error");
        }
    }
}

更新

下面的简单代码允许我选择一个目录并单击打开,这将在请求时返回选择作为所选文件的目录...

JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (choose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    System.out.println(choose.getSelectedFile());
}