在SpringBoot 2.0.1.RELEASE应用程序中读取文件

en *_*ris 3 java spring spring-mvc java.nio.file spring-boot

我有一个SpringBoot 2.0.1.RELEASE mvc应用程序.在资源文件夹中,我有一个名为/ elcordelaciutat的文件夹.

在控制器中我有这个方法来读取文件夹中的所有文件

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;
Run Code Online (Sandbox Code Playgroud)

运行应用程序.来自Eclipse工作正常,但是当我在Windows Server中运行应用程序时出现此错误:

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 
Run Code Online (Sandbox Code Playgroud)

我解压缩生成的jar文件,文件夹就在那里!

和文件夹的结构是

elcordelaciutat/folder1/*.txt
elcordelaciutat/folder2/*.txt
elcordelaciutat/folder3/*.txt
Run Code Online (Sandbox Code Playgroud)

phi*_*sch 9

从Eclipse启动项目时,生成的类文件和资源实际上只是硬盘驱动器上的文件和文件夹.这就是为什么它可以使用File类迭代这些文件.

构建时jar,所有内容实际上都是ziped并存储在单个存档中.您不能再使用文件系统级工具访问,因此您的FileNotFound例外.

使用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")) {
        // ...
   }
}
Run Code Online (Sandbox Code Playgroud)