Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files in a SpringBoot 2.0.1.RELEASE app

I have a SpringBoot 2.0.1.RELEASE mvc application. In the resources folder I have a folder named /elcordelaciutat.

In the controller I have this method to read all the files inside the folder

ClassLoader classLoader = this.getClass().getClassLoader();
        Path configFilePath = Paths.get(classLoader.getResource("elcordelaciutat").toURI());    

        List<String> cintaFileNames = Files.walk(configFilePath)
         .filter(s -> s.toString().endsWith(".txt"))
         .map(p -> p.subpath(8, 9).toString().toUpperCase() + " / " + p.getFileName().toString())
         .sorted()
         .collect(toList());

        return cintaFileNames;

running the app. from Eclipse is working fine, but when I run the app in a Windows Server I got this error:

java.nio.file.FileSystemNotFoundException: null
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
    at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
    at java.nio.file.Paths.get(Unknown Source)
    at 

I unzipped the generated jar file and the folder is there !

and the structure of the folders is

elcordelaciutat/folder1/*.txt
elcordelaciutat/folder2/*.txt
elcordelaciutat/folder3/*.txt
like image 386
en Peris Avatar asked Dec 03 '22 20:12

en Peris


1 Answers

When you start your project from Eclipse, the generated class files and resources are actually just files and folders on your hard drive. This is why it works to iterate over these files with the File class.

When you build a jar, all content is actually ziped and stored in a single archive. You can not access is with file system level tools any more, thus your FileNotFound exception.

Try something like this with the JarURL:

JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
    JarEntry e = entries.nextElement();
    if (e.getName(). endsWith("txt")) {
        // ...
   }
}
like image 58
phisch Avatar answered Dec 21 '22 10:12

phisch