gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:44:01 25 4
gpt4 key购买 nike

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

已更新

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

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

关于java - 如何让 JFileChooser 将文件夹视为目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com