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?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290

1 Answers1

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 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! – Wayne Werner Dec 10 '13 at 19:19
  • @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. – Sotirios Delimanolis Dec 10 '13 at 20:21
  • 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 ;) – Wayne Werner Dec 10 '13 at 20:29
  • Awesome. Had the same problem. – Shashi Nov 18 '16 at 10:09