首页 > 解决方案 > 从 Spring Boot 中读取文件夹会导致 FileNotFound 异常

问题描述

我正在尝试将我的 spring 应用程序移动到 spring boot

在我早期的 spring 应用程序中,我有两个模块 core 和 war。在核心中,该模块被添加为战争中的依赖项。在核心模块中,我读取了资源中指定的文件夹(遍历嵌套文件夹并加载文件)。当我以前将它作为 tomcat 运行时,这曾经可以工作。

现在我已将我的应用程序迁移到 Spring Boot。读取文件夹在 IDE 中有效,但是当我尝试将其运行为

java -jar dnow/war/target/war.jar它给了我一个错误

java.io.FileNotFoundException: class path resource [datasources] cannot be resolved to absolute file path because it does not reside in the file system: 
       jar:file:/Users/kkadam/Work/repos/Project/dnow/war/target/war.jar!/BOOT-INF/classes!/datasources

我的代码如下

public static File[] getListOfFiles(String folder) {
        File file;
        File[] listFiles = null;
        String property = Utils.getConfDirectoryPath();
        if (!Utils.isEmpty(property)) {
            try {
                if (!property.endsWith("/"))
                    property = property + "/";
                file = new File(property + folder);
                listFiles = file.listFiles();
            } catch (Exception e) {
                logger.info("Folder " + folder + "does not found. Reading from resources");
            }
        }
        if (listFiles != null)
            return listFiles;
        else {
        return listFilesFromClassPath(folder);
        }
    }

    public static File[] listFilesFromClassPath(String folder) {
        File file;
        URL url = FileUtils.class.getClassLoader().getResource(folder);
        file = new File(url.getPath());
        return file.listFiles();
    }

标签: javaspringspring-boot

解决方案


推荐阅读