-1

I am using spring-boot. and want to load resources from directory. following code works fine for filesystem environment. But gives FileNotFoundException when working with Jar,because Spring tries to access a file system path, but it can not access a path in JAR.

@EnableAutoConfiguration
@Configuration
public class Application implements CommandLineRunner {

    @Autowired
    private MongoDBMigrator migrator;

    @Autowired
    private ApplicationContext ctx;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
            migrator.runScripts(ctx.getResources("classpath:db/*.js"));
    }   
}

what need to be done to make it work with jar as well

1 Answers1

0

You could use something like this:

InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileFromJarFile);

If test.txt was in the root of your JAR file, you'd use:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("test.txt");

assumes the class is in the same JAR file as the resource, I believe

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • InputStream is used for single resource. I want to read multiple resources as file not as inputstream. because for further operation i need file path , filename etc – suvarna Chavan Mar 01 '17 at 08:28
  • @suvarnaChavan Yes it is used for single resource use can use a List of InputStream if the Resource name is same – Rahul Singh Mar 01 '17 at 08:30