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,774
  • 1
  • 21
  • 47
rura6502
  • 303
  • 2
  • 15

2 Answers2

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
  • 152
  • 1
  • 11
  • 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