1

When I execute the jar using this command java -jar myapp.jar, I met the FileNotFoundException.

My project is a basic Gradle java application. I put the file in ROOT/src/main/resources/testfile/test1.txt. And I tried to run the code in IDE to check the file exists using classpath.

File file = ResourceUtils.getFile("classpath:testfile/test1.txt");
System.out.println(file.exists());

This is true, but when I executed build file that is the result of command 'gradle build', I met the FileNotFoundException. I can see the file(\BOOT-INF\classes\testfile\test1.txt) when I unarchive the jar.

Actually, I want to deploy the spring boot jar with the sample file and I will put the code for initializing. please help. thanks.

Ashish Ratan
  • 2,838
  • 1
  • 24
  • 50
rura6502
  • 365
  • 2
  • 15

3 Answers3

2

You cannot read the resources inside a jar as java.io.File as it says in the link that @Shailesh shared

InputStream is = this.getClass().getClassLoader().getResourceAsStream("classpath:testfile/test1.txt")) 

Read the file as input stream and then may be convert it to String and then convert it to a class if needed.

user12047085
  • 162
  • 1
  • 12
  • 2
    the following often creates less trouble: `MyClass.class.getResourceAsStream("/testfile/test1.txt")` – Puce Oct 11 '19 at 14:48
2

Assuming You actually want to read the file rather than trying to address the resource use the class loader:

    InputStream in = getClass().getResourceAsStream("/testfile/test1.txt");
    BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
    String line = null;
    while( (line = reader.readLine() ) != null )
      System.out.println("Line: " + line);

that worked for me

Oeg Bizz
  • 104
  • 6
0

'this.getClass().getClassLoader().getResourceAsStream()' is a good choice

I meet the same question. And only difference is that I want the return type —— String, after reading a file. So, I find a useful api —— this.getClass().getClassLoader().getResource(String name).

String read = null;
URL resource = this.getClass().getClassLoader().getResource("static/facility-tree.json");
CharSource charSource = Resources.asCharSource(resource, Charset.defaultCharset());
read = charSource.read();

CharSource and Resources are from Guava, so you need to add dependency in pom.xml.

<!--guava->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
Hopkin
  • 1
  • 1