Reputation: 385
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.
Upvotes: 1
Views: 345
Reputation: 1
'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>
Upvotes: 0
Reputation: 114
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
Upvotes: 2
Reputation: 162
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.
Upvotes: 2