【发布时间】:2019-01-29 11:51:47
【问题描述】:
我想从资源文件夹的子目录中读取文件。 我遇到了 jar 执行的问题。
这是我的目录结构。
src/main/resources
|_ Conf
|_ conf1
|_ config.txt
|_ conf2
|_ config.txt
在这里,我试图从Conf 文件夹的所有子目录中读取config.txt 文件。我不知道Conf 会有哪些子目录。我知道 Conf 之前的类路径。所以,我将给出类路径直到Conf 并尝试获取子目录和文件。
我尝试使用ClassPathResource 来实现这一点。如果它是文件,这工作正常。我在目录方面遇到问题。我正在使用getFile api 获取目录路径以遍历该目录以查找导致 jar 执行问题的子目录。
这是我的代码:
下面的代码是读取Conf文件夹中的子目录。
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
ClassPathResource classPathResource = new ClassPathResource("Conf");
File dir = classPathResource.getFile();
Files.walk(Paths.get(dir.toString()))
.filter(Files::isDirectory)
// This is to exempt current dir.
.filter((Path p)->!p.toString().equals(dir.toString()))
.forEach(f-> {list.add(readDirectory(f.toString()));});
读取每个子目录。
public Map<String, String> readDirectory(String dir) {
Map<String, String> map = new HashMap<String, String>();
String confDir = dir.substring(dir.lastIndexOf(File.separator)+1);
try {
Files.list(Paths.get(dir))
.filter(f->f.toString().matches(".*conf\\.txt"))
.forEach(file ->approvedTermsMap.put
(confDir,readFile(file.toFile())));
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
读取文件:
public String readFile(File confFile) {
StringBuffer terms = new StringBuffer();
try (BufferedReader reader = new BufferedReader(new
FileReader(confFile)))
{
reader.lines().forEach(term->
terms.append(term + "|"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return terms.toString();
}
在这里,我不应该使用classPathResource.getFile() 来获取绝对路径,因为它会尝试在文件系统中查找文件,这在 jar 的情况下将无法使用。所以,我需要另一种方法来获取资源目录的绝对路径。我必须将它传递给File.walk api 才能找到子目录和文件。
【问题讨论】:
标签: java maven spring-boot