如何在Gradle项目中获取resources目录下的所有文件名?
如何自动获取resources目录下的所有文件名?
当然可行,下面给你覆盖IDE本地运行和打包成Jar后运行两种场景的实现方案,直接替换你代码里的手动文件名列表即可:
1. 实现自动获取文件名的工具方法
import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public static List<String> getFileNamesInResources() throws IOException { List<String> fileNames = new ArrayList<>(); ClassLoader classLoader = ClassLoader.getSystemClassLoader(); // 获取resources根目录的URL(如果要指定子目录,比如"json/",就把参数改成对应路径) URL resourceUrl = classLoader.getResource(""); if (resourceUrl == null) { return fileNames; } String protocol = resourceUrl.getProtocol(); if ("file".equals(protocol)) { // 本地文件系统场景(IDE运行或未打包的classes目录) URI uri = resourceUrl.toURI(); Path dirPath = Paths.get(uri); // 遍历目录下的所有文件,过滤出.json后缀的文件(不需要过滤可以去掉filter条件) Files.list(dirPath) .filter(Files::isRegularFile) .filter(path -> path.getFileName().toString().endsWith(".json")) .forEach(path -> fileNames.add(path.getFileName().toString())); } else if ("jar".equals(protocol)) { // Jar包场景(打包后运行) String jarPath = resourceUrl.getPath().substring(5, resourceUrl.getPath().indexOf("!")); try (JarFile jarFile = new JarFile(jarPath)) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); // 过滤根目录下的.json文件,排除子目录和文件夹(需要递归子目录可以调整判断逻辑) if (!entry.isDirectory() && entryName.endsWith(".json") && !entryName.contains("/")) { fileNames.add(entryName); } } } } return fileNames; }
2. 修改你的原代码
把手动指定文件名的部分替换成调用上面的方法,同时优化资源流的处理(用try-with-resources自动关闭流,避免资源泄漏):
import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.List; public static void loadFiles() throws IOException { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); List<String> fileNames = getFileNamesInResources(); // 替换手动列表 for (String fileName : fileNames) { try (InputStream is = classLoader.getResourceAsStream(fileName)) { if (is == null) { System.out.println("未找到文件:" + fileName); continue; } String content = new String(is.readAllBytes(), StandardCharsets.UTF_8); System.out.println(content); } // try-with-resources会自动关闭InputStream } }
注意事项
- 如果需要获取resources下子目录里的文件,比如
resources/json/下的文件,只需要把classLoader.getResource("")改成classLoader.getResource("json/"),同时调整Jar场景下的路径判断逻辑(比如允许entryName包含json/前缀)。 - 代码里默认只过滤
.json后缀的文件,不需要过滤的话可以删掉对应的filter条件。 - 打包成Jar后,资源文件会被包含在Jar包内,这种场景下不能用File类直接访问,必须通过JarFile遍历。
内容的提问来源于stack exchange,提问作者motgochim
相关产品推荐
相关产品推荐

