簡體   English   中英

如何讓JFileChooser將文件夾視為目錄?

[英]How do I get JFileChooser to treat a folder as a directory?

我正在嘗試使用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");
        }
    }
  }
}                            

從您的代碼中,您似乎不需要。 只需允許用戶選擇您要處理的目錄並使用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");
        }
    }
}

更新

下面的簡單代碼使我可以選擇一個目錄,然后單擊Open ,這將在請求時返回選擇為所選文件的目錄...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM