Will Byers Will Byers - 1 month ago 10
Java Question

How to read text file on base level of java maven project

I want to read a file into a String variable that is located at the base level of my Maven project.

enter image description here

In this example I'm trying to read the "somerando.sql" file.

I've been trying to use:

Path path = Paths.get("/myproj/somerando.sql");
String sql = new String(Files.readAllBytes(path));


but that's not getting it. Is there a way I can read the file in from here without using it's absolute path on the computer?

Answer

Maven has some conventions, you should try to follow them. These are helpful.

Besides, after development, the application doesn't live in a Maven project but in a component (Jar/war, etc...). So, to avoid absolute path, you should place your files required for application or testing in matching classpath folders.

if your file is for testing, you could move it to the place reserved by Maven to address this need : yourMavenProject/src/test/resources

If your file is for the application, you could move it to the place reserved by Maven to address this need : yourMavenProject/src/main/resources

Now you can access it with :

Path path = Paths.get(YourClass.class.getResource("filter.xml").toURI());
Comments