0

Opening Files in Maven is best done like this:

Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");

or this:

InputStream in = getClass().getResourceAsStream("db.properties");

How do I open a folder in Maven and how am I able to iterate through it?

user2368505
  • 416
  • 3
  • 16
  • What do you mean by "in Maven"? Are you writing a Maven plugin? – Thilo May 10 '13 at 03:28
  • or do you need something like this: http://stackoverflow.com/questions/7953600/list-of-resources-in-a-folder-of-jar-file or this: http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory?lq=1 – Thilo May 10 '13 at 03:29
  • Please see [What is the difference between Class.getResource() and ClassLoader.getResource()?](http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource) – Charlee Chitsuk May 10 '13 at 03:44

1 Answers1

1

I'm assuming by 'in Maven' you mean 'while writing a Maven plugin'.

It usually makes sense to make file paths as configurable parameters:

@Mojo(name = "mygoal", defaultPhase = LifecyclePhase.PREPARE_PACKAGE)
public class MyPlugin extends AbstractMojo {
    @Parameter(defaultValue="${basedir}/src/main/resources/db.properties")
    public File dbcfg;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        Properties cfg = new Properties();
        FileReader cfgReader = new FileReader(dbcfg);
        try {
            cfg.load(cfgReader);
        }finally{
            IOUtils.closeQuietly(cfgReader); 
        }
        /* .... */
    }

}

Note that you get to use maven expression in the default value.

rzymek
  • 9,064
  • 2
  • 45
  • 59