As khmarbaise pointed out already the design of this application is completely messed up. I found an ugly workaround but it makes things work and is well tested.
The main problem is, that different modules need to access the same files. Unfortunately the files cannot be processed as streams (which would make things a lot easier) since 3rd party libraries need an actual file handle. And receiving this (.getFile()
) is the problem as Tunaki said already. The reason it was working in mvn test
is that, these tests are run before the application is packed. By observing the path of the .getResource()
it shows a change to jar://
when it's packed which makes it impossible to get actual file handles since there are no files anymore. However, it is possible to receive InputStreams.
The workaround is simple:
Receiving the files as input streams, writing them to a temporary directory after the application is started.
private File copyResourceIntoTempFile(String resource, File target) throws IOException {
InputStream input = getClass().getResourceAsStream(resource);
OutputStream out = new FileOutputStream(target);
int read;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
//target.deleteOnExit();
if (!target.exists()) {
throw new FileNotFoundException("Error: File " + target + " not found!");
}
return target;
}
It is also possible to iterate over the files of a directory:
InputStream in = this.getClass().getResourceAsStream(resource);
BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = rdr.readLine()) != null) {
this.copyResourceIntoTempFile(resource+"/"+line, new File(dir, line));
}
rdr.close();
I know that this is by far not the nicest solution. However, the solution of the guy that started the project was to ensure that some files are in the directory (manually) wherever the application runs. After some cumbersome work with deploying the application it got refactored to download the needed files and unzip them which took forever.