Search code examples
javamavenpathjboss

How can I make a file visible both when project is deployed on a server and when its classes are run from test classes?


If I use a file calling it directly:

FileInputStream fileInputStream = new FileInputStream("SR02_pattern.xls");

( the file is in \apv\main-app directory), it won't be deployed, and of course, it won't be seen when the project will be run on the server.

If I put the file in the /apv/main-web/WEB-INF/classes/ directory, it will be deployed and I can call it by

InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("SR02_pattern.xls")

when the project is deployed on the server, but that line won't read the file in the case the class was run from the test.

Probably, the place where the file will be looked for by getResourceAsStream("SR02_pattern.xls"), is set by some system properties and I can use them, but I don't know which properties can help.

How can I read the file in both cases by the same code without passing it as a parameter into the class?

There are many answers on SO for either of those cases, but I couldn't find one that works for both. The default paths for both cases are different.

Of course, I can put the file in both places, and in case the file is not in the first folder, look it in the second, as I am doing now, but upkeeping two copies is prone to errors and I desire to use better style.


Solution

  • You should use this.getClass().getResourceAsStream('/SR02-pattern.xl') for all parts in test as well in production code. The / defines the root directory for the resources.

    The files you would like to read should be located in src/main/resources. This will result in the final war package at the location WEB-INF/classes.