有没有一种快速的方式可以使用Java在设备上获取所有音频文件?

huangapple go评论60阅读模式
英文:

Is there a fast way to get all audio files on a device using java?

问题

public static void findAudio(File currentDir) {
    File[] filesInDir = currentDir.listFiles();
    if (filesInDir != null){
        if (filesInDir.length == 0){
            return;
        }
        else {
            for (File file : filesInDir) {
                if (!file.isHidden()) {
                    if (file.isDirectory()) {
                        findAudio(file);
                    }
                    if (file.canRead()) {
                        if (file.getName().endsWith(".mp3")) {
                            System.out.println(file.getPath());
                        }
                    }
                }
            }
        }
    }
    else {
        System.out.println(currentDir.getPath() + " is null -- skipping");
    }
}
英文:

Beginner Java programmer here. I'm trying to make a simple mp3 player on my mac (and eventually Android) and I would like to have it auto recognize all the music (mp3) that's already on your device.

I have a simple for loop set up that starts at the home directory and loops through all other directories looking for mp3s. I have yet to see it complete the loop as I always have to force stop it because it goes on for so long. I could just exclude some folders because placing music in them just wouldn't make sense, but I feel like there is a better approach.

Are there any other methods that I could look into that are faster and/or more efficient than a for loop?

I'm also curious about how the finder in mac works. For Example, when I use the finder to look for all the mp3 files on my mac, the results only take a couple of seconds to show up and all I need is to enter in some search criteria. If someone could point me in the direction of how to accomplish something similar to this that would be great, I'll take any input I can get!

public static void findAudio(File currentDir) {
    File[] filesInDir = currentDir.listFiles();
    if (filesInDir != null){
        if (filesInDir.length == 0){
            return;
        }
        else {
            for (File file : filesInDir) {
                if (!file.isHidden()) {
                    if (file.isDirectory()) {
                        findAudio(file);
                    }
                    if (file.canRead()) {
                        if (file.getName().endsWith(".mp3")) {
                            System.out.println(file.getPath());
                        }
                    }
                }
            }
        }
    }
    else {
        System.out.println(currentDir.getPath() + " is null -- skipping");
    }
}

答案1

得分: 1

首先要注意,检查文件扩展名比检查文件是否可读所花费的时间更少。

此外,您可以在Java 8中使用Files.walkFileTree方法进行此操作。

在Oracle的网站上有一个关于如何使用它的教程:https://docs.oracle.com/javase/tutorial/essential/io/walk.html

代码将类似于这样:

Files.walkFileTree(Paths.get(sourcePath), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) {
        if (filePath.toString().endsWith(".mp3") && filePath.toFile().canRead()) {
            System.out.println(filePath.toString());
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.err.println("Failed reading \"" + file.toString() + "\" -- skipping");
        return FileVisitResult.CONTINUE;
    }
});

SimpleFileVisitor类是FileVisitor接口的简化实现,具有访问所有文件并重新抛出I/O错误的默认行为。

如果出现I/O错误,我们只会将文件路径打印到默认错误流,并继续文件处理。

如果没有错误,文件扩展名是“.mp3”(如上所述首先检查扩展名),并且文件可读,则将文件路径打印到默认输出流(您还可以执行其他操作,例如将其添加到媒体文件列表中)。

英文:

First things first, checking file extension is less time consuming than checking if the file is readable.

Additionally, you can use Files.walkFileTree method added in Java 8 for this.

There is a tutorial at oracle's site on how to use it: https://docs.oracle.com/javase/tutorial/essential/io/walk.html

The code would look something like this:

Files.walkFileTree(Paths.get(sourcePath), new SimpleFileVisitor&lt;&gt;() {
    @Override
    public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) {
        if (filePath.toString().endsWith(&quot;.mp3&quot;) &amp;&amp; filePath.toFile().canRead()) {
            System.out.println(filePath.toString());
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.err.println(&quot;Failed reading \&quot;&quot; + file.toString() + &quot;\&quot; -- skipping&quot;);
        return FileVisitResult.CONTINUE;
    }
});

SimpleFileVisitor class is a simplified implementation of FileVisitor interface with default behavior to visit all files and re-throw I/O Errors.

In case there is an I/O error we only print file path to default error stream and continue with file processing.

In case there are no errors, the file extension is ".mp3" (checking extension first as noted above), and the file is readable we print file path to the default output stream (you can also do other stuff, like adding it to list of media files)

答案2

得分: 0

import java.io.*;

public static void extract(String p) {
    File f = new File(p);
    File l[] = f.listFiles();
    for(File x : l){
        if (x==null) return;
        if (x.isHidden()||!x.canRead()) continue;
        if (x.isDirectory()) extract(x.getPath());
        else if (x.getName().endsWith(".mp3"))
            System.out.println(x.getPath()+"\\"+x.getName());
    }
}
英文:
import java.io.*;

public static void extract(String p) {
    File f = new File(p);
    File l[] = f.listFiles();
    for(File x : l){
        if (x==null) return;
        if (x.isHidden()||!x.canRead()) continue;
        if (x.isDirectory()) extract(x.getPath());
        else if (x.getName().endsWith(&quot;.mp3&quot;))
        System.out.println(x.getPath()+&quot;\\&quot;+x.getName());
    }
}

huangapple
  • 本文由 发表于 2020年8月15日 15:46:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63423781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定