JFile Chooser 决定是否选择目录或文件

发布于 2024-09-08 06:02:48 字数 198 浏览 5 评论 0原文

我的主要目标:

如果用户选择一个目录,它会扫描整个文件夹中的 mp3 文件并返回它们。如果他选择了一些 mp3 文件,它就会返回它们。

返回选定的文件很容易,但扫描目录中的 mp3 并不像我最初想象的那么容易。 我认为要做到这一点,我首先要决定用户是否选择了文件或目录,但是如何呢?因为我可以使用 getSelectedFiles() 来获取两者。

My main goal:

if the user selects a directory it scans the whole folder for mp3 files and returns them. If he selects some mp3 files it returns them.

To return the selected files was an easy one but to scan the directory for mp3's isn't as easy as I first thought.
And I think to do that I first new to decide if the user selected a file or directory, but how? Since I can get both with getSelectedFiles().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清醇 2024-09-15 06:02:48

您可以使用 File.isDirectory()File.isFile() 来确定 File 分别是目录或普通文件。

You can use File.isDirectory() and File.isFile() to determine if a File is a directory or a normal file, respectively.

蛮可爱 2024-09-15 06:02:48

由于您希望用户仅选择一个目录,因此您需要自己查找 mp3 文件。

您可以递归地遍历目录查找以“.mp3”结尾的文件。

public static void findMp3s(File root, List<File> toBuildUp) {
    // if the File is not a directory, and the name ends with mp3
    // we will add it to our list of mp3s
    if (!root.isDirectory() && root.getName().endsWith("mp3")) {
        toBuildUp.add(root);
        return;
    }
    if (!file.isDirectory())
        return;
    // Now, we know that root is a Directory
    // We will look through every file and directory under root,
    // and recursively look for more mp3 files
    for (File f: root.listFiles()){
        findMp3s(f, toBuildUp);
    }
}

上述方法将递归遍历所有目录,并使用该目录下的每个 mp3 文件填充 toBuildUp

您将像这样调用此方法:

List<File> allMp3s = new ArrayList<File>();
findAllMp3s(selectedDirectory, allMp3s);

Since you want your users to select just a directory, you will need to find the mp3 files yourself.

You can recursively traverse a directory looking for files that end in ".mp3".

public static void findMp3s(File root, List<File> toBuildUp) {
    // if the File is not a directory, and the name ends with mp3
    // we will add it to our list of mp3s
    if (!root.isDirectory() && root.getName().endsWith("mp3")) {
        toBuildUp.add(root);
        return;
    }
    if (!file.isDirectory())
        return;
    // Now, we know that root is a Directory
    // We will look through every file and directory under root,
    // and recursively look for more mp3 files
    for (File f: root.listFiles()){
        findMp3s(f, toBuildUp);
    }
}

The preceding method will recursively traverse all directories and populate toBuildUp with every mp3 file under that directory.

You will call this method like:

List<File> allMp3s = new ArrayList<File>();
findAllMp3s(selectedDirectory, allMp3s);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文