2

Just wanted to know which is the best way to read a file that may be in the classpath.

The only thing i have is a property with the path of the file. For exemple:

  • filepath=classpath:com/mycompany/myfile.txt
  • filepath=file:/myfolder/myfile.txt

Which is the best way to load an InputStream from that property?

Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419

4 Answers4

3

You can use the URL method openStream, which returns an InputStream you can use to read your file. The URL will work for files inside and outside the JAR. Just take care to use a valid URL.

Gilberto Torrezan
  • 5,113
  • 4
  • 31
  • 50
3

You'd have to detect it manually. Once you have done so, to obtain a resource from the classpath in the form of an inputstream:

class Example {
    void foo() {
        try (InputStream in = Example.class.getResourceAsStream("/config.cfg")) {
            // use here. It'll be null if not found.
        }
    }
}

NB: Without the leading slash, it's relative to the same directory (within the jar if need be) that contains your Example.class file. With the leading slash it is relative to the root of the classpath (the root of the jar, the root of your 'bin' dir, etc).

Naturally, there is no way to get an outputstream; as a rule, most entries in the classpath aren't writable.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1

Well I'd simply use the String methods startsWith(String sequence) and check if it starts with classpath or filepath and call an approriate method from there to do the work:

String str=//extracted property tag
if(str.startsWith("filepath")) {
 //simply intialize as URL and get inputstream from that
 URL url =new URL(str);
 URLConnection uc = url.openConnection(); 
 InputStream is=uc.getInputStream();
} else if(str.startsWith("classpath")) {
//strip the classpath  and then call method to extract from jar
}

See here for extracting resources from in a jar.

Community
  • 1
  • 1
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
0

When using spring org.springframework.core.io.DefaultResourceLoader is a solution:

@Resource DefaultResourceLoader defaultResourceLoader;
defaultResourceLoader.getResource(path).getInputStream()
wutzebaer
  • 14,365
  • 19
  • 99
  • 170