0

Hello one of the parts of a program i'm working on requires the ability to search through a directory. I understand how using a path variable works and how to get to a directory; but once you are in the directory how can you distinguish files from one another? Can we make an array/or a linked list of the files contained within the directory and search using that?

In this specific program the goal is for the user to input a directory, from there go into sub-directory and find a file that ends with .mp3 and copy that to a new user created directory. It is certain that there will only be one .mp3 file in the folder.

Any help would be very much appreciated.

  • Have you attempted any part of this so far? It would be helpful if you posted your code. Do you want the user to do this through point-and-click UI, or by typing commands? – deyur Oct 02 '14 at 21:14

3 Answers3

1

Seeing what you say, I will suppose that you use the java7 Path api.

To know if a path is a directory or a simple file, use Files.isDirectory(Path)

To list the files / directories in your directory, use Files.list(Path)

The javadoc of the Files class : http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

If you use the "old" java.io.File api, then you have a listFiles method, which can take a FileFilter as argument to filter, for exemple, only the files ending with ".mp3".

Good luck

0

You can use the File object to represent your directory, and then use the listFiles() (which return an array of files File[]) to retrieve the files into that directory.

If you need to search through subdirectories, you can use listFiles() recursively for each directory you encounter.

As for the file extension, the Apache Commons IO library has a neat FileFilter for that: the SuffixFileFilter.

Alexis Leclerc
  • 1,303
  • 1
  • 16
  • 26
0

Get Files as so:

List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
for (File file : files) 
    if (file.isFile()) 
        results.add(file.getName());

If you want the extension:

public static String getExtension(String filename){
    String extension = "";
    int i = fileName.lastIndexOf('.');
    if (i > 0) 
        extension = fileName.substring(i+1);
    return extension;
}

There are other ways to get file extensions listed here but they usually require a common external library.

Community
  • 1
  • 1