问题
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?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
When using spring org.springframework.core.io.DefaultResourceLoader
is a solution:
@Resource DefaultResourceLoader defaultResourceLoader;
defaultResourceLoader.getResource(path).getInputStream()
来源:https://stackoverflow.com/questions/12409478/get-inputstream-from-a-file-that-may-or-not-be-in-the-classpath