Reputation: 509
I am writing a program where i want all my audio files (.mp3,.wav etc ) files in an arrayList my code looks like this:
public class FileTest
{
public ArrayList<File> list(String directoryName, ArrayList<File> files)
{
File directory = new File(directoryName);
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile() **&& (if the file is an audio file)**) {
files.add(file);
} else if (file.isDirectory()) {
list(file.getAbsolutePath(), files);
}
}
return files;
}
public static void main(String[] args)
{
FileTest fileTest = new FileTest();
ArrayList<File> files = new ArrayList<File>();
files = fileTest.list("/media/kumuda/D804C38204C361DC/Program Files",files);
for(File file : files)
{
System.out.println(file.getAbsolutePath());
}
}
}
I want to check if the file is an audio file before adding it to my arraylist. I searched for api's and came across Apache Tika library. but i am not getting how it exactly works. Please can anyone help me ?
Upvotes: 1
Views: 1296
Reputation: 121750
Here is how you would do that using Files
.
First, create a FileVisitor
. Extend SimpleFileVisitor
since it is enough for your needs:
public final class AudioFileCollector
extends SimpleFileVisitor<Path>
{
private final List<Path> fileList;
public AudioFileCollector(final List<Path> fileList)
{
this.fileList = fileList;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
// We know this is a regular file here, so now we just need to check the type
switch (Files.probeContentType(file)) {
case "audio/x-wav": // wav file
case "audio/mpeg": // mp3
fileList.add(file);
default:
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e)
throws IOException
{
if (e != null)
throw e;
return FileVisitResult.CONTINUE;
}
Then walk your directory with this visitor:
final Path baseDir = Paths.get("...");
final List<Path> fileList = new ArrayList<>();
final FileVisitor<Path> collector = new AudioFileCollector(fileList);
Files.walkFileTree(baseDir, collector);
Done!
Note the use of Files.probeContentType()
.
Solution with Java 8 (I guess it could be better):
public final class Main
{
public static void main(final String... args)
throws IOException
{
final List<String> extensions = Arrays.asList(".mp3", ".wav");
final Path start = Paths.get("...");
Files.walk(start).map(Object::toString)
.filter(s -> extensions.stream().anyMatch(s::endsWith))
.forEach(System.out::println);
}
}
If you want to collect in a list, replace .forEach()
with .collect(Collectors.toList())
.
Upvotes: 2
Reputation: 6228
The easiest way would be to use ragex and check if the filename matches a pattern. (http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
Something like
if( Pattern.matches("[a-zA-Z0-9]+.mp3",file) || Pattern.matches("[a-zA-Z0-9]+.wav",file) )
{
// your code here
}
Upvotes: 0