4

I was using the following code to read a file from the classpath:

Files.readAllBytes(new ClassPathResource("project.txt").getFile().toPath())

This worked fine when project.txt was in src/main/resources of my WAR. Now I refactored code and moved certain code to a JAR. This new JAR now includes src/main/resources/project.txt and the code above. Now I get the following exception when reading the file:

java.io.FileNotFoundException: class path resource [project.txt]
cannot be resolved to absolute file path because it does
not reside in the file system:
jar:file:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib/viewer-1.0.0-SNAPSHOT.jar!/project.txt

I'm still executing the WAR in a Tomcat container.

How can I fix this?

TwiN
  • 3,554
  • 1
  • 20
  • 31
Jelly Orns
  • 197
  • 1
  • 2
  • 8

1 Answers1

5

You cant refer the file from jar the way you do it in from resources. Since the file is packaged inside the jar you need to read it as resource. You have to read the file as resource using classloader.

sample code:

ClassLoader CLDR = this.getClass().getClassLoader();
InputStream inputStream = CLDR.getResourceAsStream(filePath);

If you are using java 8 and above then you can use below code using nio to read your file:

final Path path = Paths.get(Main.class.getResource(fileName).toURI());
final byte[] bytes = Files.readAllBytes(path);
String fileContent = new String(bytes, CHARSET_ASCII);
Sangam Belose
  • 4,262
  • 8
  • 26
  • 48