Reputation: 1464
I have a maven project with typical project structure. At the base of the project, I have a directory names res that has some resources (> 500 MB). I am trying to use
this.class().getClassLoader().getResourceAsStream("res/xxx")
this code fragment to read from that folder, but it returns a null resource stream. I have a few workarounds below, but none of these are acceptable due to reasons explained below.
Is there some way I can read the res folder from projects base directory? Is there some setting in pom.xml file that can help me with that?
Upvotes: 3
Views: 13705
Reputation: 3281
If you use this.class().getClassLoader().getResourceAsStream("/res/xxx")
, it is going to try to load resources from the classpath. If that's not want you want to do, you're going to need to specify an absolute path.
If you don't want the resource built into your JAR, I'd suggest having a different maven project with the file in it, under the src/main/resources
directory. This will create a jar file with the file in it, which will be ~500MB.
After this, you can include a dependency on this project in your project containing your application code. This will then be able to reference it from the jar file using getResourceAsStream(...)
.
If you don't want this large jar file to ship with your application, make sure you mark the dependency with <scope>provided</scope>
.
You will need to take the file location as a parameter in your main method, and then use new File("C:\\path\\to\\your\\file.txt")
and then use a FileReader
to read it in.
Upvotes: 1
Reputation: 13836
Use this.class().getClassLoader().getResourceAsStream("/res/xxx")
and then you will be reading from the root of the classpath irrespective of the actual file/folder location in windows or Linux. This is actually one of the safest ways to read files especially when you do not know how your application will eventually be deployed.
It means though that your classpath must include the parent of res and that res/ must be copied over when you deploy your app
Otherwise, if you want to use relative paths, try this snippet (taken from this SO answer):
String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");
Upvotes: 5