Issue
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.
Solution
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
Answered By - Oeg Bizz
Answer Checked By - David Goodson (JavaFixing Volunteer)