read .html file from resources folder on server in spring boot

Viewed 779

I am trying to read demo.html file from resources in spring boot. I have tried this codes but it is working in local-only not on server :

val demoFile = new File(this.getClass.getClassLoader.getResource("foo/demo.html").getFile)
val demoFile = new File(ClassLoader.getSystemClassLoader.getResource("foo/demo.html").getFile)
val demoFile = new File(Thread.currentThread().getContextClassLoader.getResource("foo/demo.html").getFile)

on server I am getting FileNotFoundException

thank you.

1 Answers

It works locally because the file demo.html exists on your local machine. You can find it in a build folder or whatever your IDE uses to compile the code.

When you run your project on a server, you have only your project jar file, for example, project.jar. There is not demo.html file on a server.

demo.html is located inside project.jar file. project.jar is a simply ZIP archive. So you need a way to get a file from a ZIP archive (your project.jar).

The simplest way is to use streams. You can read a file, for example, in a string.

If you need to parse a file (it can be JSON, XML or HTML) you can pass a stream directly to the parsing library.

Also don't forget to close the stream (if it is not closed by the library, of course).

https://www.baeldung.com/spring-classpath-file-access

Also you can copy a file from a jar to the TEMP folder and access it as an usual file.

Related