Jump to content

Question about interfaces and user input

I'm writing a program that searches through a folder to look for all files with extensions specified by the user.

eg. find all .jpg and .png files in f:/pictures

 

I was able to find some sample code online that can accomplish this task, but only if the file types are specified at compile time (eg.only txt files in the example below). How can modify the code such that I can feed user input into the type of files that are accepted?

 

import java.io.File;
import java.io.FilenameFilter;

public class Filter {

  public File[] finder( String dirName){
    File dir = new File(dirName);

    return dir.listFiles(new FilenameFilter() {
     public boolean accept(File dir, String filename){
     { return filename.endsWith(".txt"); }
    } );

  }

}

Link to comment
https://linustechtips.com/topic/302216-question-about-interfaces-and-user-input/
Share on other sites

Link to post
Share on other sites

You'll want to use a main method so you can pass in the parameters at the command line (i.e. the string[] args part), also fix your damn formatting that code is ugly as hell.

I tried doing that, but I get an error saying cannot refer to a non final variable args inside an inner class defined in a different method

Link to post
Share on other sites

Pseudocode to get you started:

 

public class Filter {

    public static void main(String[] args) {

        directory = arg[0]

        for each file in directory

            if file extension one of arg[1..n] print filename

    }

}

 

I would add the extensions into a Trie for comparison. Java doesn't include a Trie though, so you'd have to write your own. HashSet would also work, but not as well. Iterate through and compare the extension to every possible extension would be worst-case n^2.

 

Look at the javadocs for:

http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.Filter.html

Files

Paths

Path

 

You should be able to write this in under 20 lines of code. I'd look at the API help: http://docs.oracle.com/javase/tutorial/essential/io/pathClass.html

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×