I have the following directory layout:
- src
- main
- java
- resources
- sql (scripts for database)
- spring (configuration)
- webapp
Within a ServletContextListener class, I want to access the files under the SQL directory and list them. Basically my problem is with the path, because I know that listing files under a directory in a nutshell is:
File folder = new File(path); File[] listOfFiles = folder.listFiles();
Maybe I could use the ServletContextEvent
Object to try and build a path to resources/sql
public void contextInitialized(ServletContextEvent event) { event.getServletContext(); //(getRealPath etc.) }
Does something exist to set that path in a relative, non-hardcoded way? Something like new File("classpath:sql")
(preferably spring if possible) or what should I do with the servletContext to point at resources/sql
?
Using java. String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System. out. println(absolutePath); assertTrue(absolutePath.
This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .
Map<String, Object> env = new HashMap<>(); try (FileSystem fs = FileSystems. newFileSystem(uri, env)) { Path path = fs. getPath("/path/myResource"); try (Stream<String> lines = Files. lines(path)) { .... } }
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
I'm assuming the contents of src/main/resources/
is copied to WEB-INF/classes/
inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).
URL sqlScriptUrl = MyServletContextListener.class .getClassLoader().getResource("sql/script.sql");
Finally, this is what I did:
private File getFileFromURL() { URL url = this.getClass().getClassLoader().getResource("/sql"); File file = null; try { file = new File(url.toURI()); } catch (URISyntaxException e) { file = new File(url.getPath()); } finally { return file; } }
...
File folder = getFileFromURL(); File[] listOfFiles = folder.listFiles();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With