1

I'm using Tomcat 7 and am learning JSP. I am trying to build a list of files in a directory with a specific extensions. I found this tutorial, and I have the following code:

package winning;

import java.io.File;
import java.io.FileFilter;
import java.util.List;
import java.util.ArrayList;

public class Winning {
    public List<String> getNames(String directory, String extension){
        final String ext = extension;
        File f = null;
        File[] names;
        List<String> results = new ArrayList<String>();

        f = new File(directory);

        FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File pathname){
                return true;
            }
        };

        names = f.listFiles(filter);

        for(File file : names){
            results.add(file.getName());
        }

        return results;
    }
}

The exception that Tomcat presents is NoClasDefFoundError, but it reports that a ClassNotFoundException is being thrown at the FileFilter filter = new FileFilter... line.

My code works perfectly fine if I get rid of that block, so I have:

...
f = new File(directory);
// used to be code here
names = f.listFiles(/*no more filter*/);
...

It looks to me like basically have the same code as the example, but it's not working. Is this tutorial just really out dated, or is there a way to use an anonymous class here?

1
  • Please post the stack trace. Commented Dec 10, 2013 at 19:01

1 Answer 1

4

When you compile a class that contains anonymous classes, there are multiple .class files generated. For example, you would have Winning.class for the top level class and Winning$1.class for the first anonymous inner class.

If you only put Winning.class in /WEB-INF/classes, then you would get a ClassNotFoundException when the code tries to load the anonymous class.

Sign up to request clarification or add additional context in comments.

4 Comments

That is in fact where it is (well, /WEB-INF/classes/winning/). Ooooohhh! Ahah. I wrote a script to manually copy Winning.class from my source directory to the /winning/ folder. Since it didn't copy Winning$1.class that is why it didn't work. Modifying my script to dump the other class file works perfectly. Thanks!
@WayneWerner You're welcome. Consider (in real life as opposed to testing a small feature) using a standard build system, like Maven, or even your IDE that will copy the class files for you.
That's excellent advice, and IRL I do, very much so. My philosophy is "do the simplest thing that could possibly work" and then build up from there. And beyond a toy example the simplest thing usually is a standard tool ;)
Awesome. Had the same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.