我正在尝试从资源文件夹中加载文件,但是在构建/打包后无法使它工作
URL databaseURL = this.getClass().getClassLoader().getResource("blacklisted.words");
List<String> blacklistedWordsDatabase = Files.readAllLines(Paths.get(databaseURL.getPath()), StandardCharsets.UTF_8);
当我从IDE中运行代码时,此方法非常有效,但是在mvn package
之后,我运行java -jar target/project-0.0.1-jar-with-dependencies.jar
并获得
java.nio.file.NoSuchFileException file:/var/www/project/target/project-0.0.1-jar-with-dependencies.jar!/blacklisted.words
但是检查存档blacklisted.words
显然在jar的根文件夹中...有关我在这里做错什么的任何提示?
答案 0 :(得分:1)
您正在使用Files.readAllLines
,它需要一个真实的文件/路径。这将在“未打包”的环境中工作,例如当您在IDE中进行测试或运行mvn test
/ mvn exec
时,但不适用于JAR,因为JAR会将文件打包在存档中。没有文件和路径!
您可以做的是获取InputStream
打包资源并使用它:
try (InputStream resource = this.getClass().getClassLoader().getResource("blacklisted.words")) {
List<String> blacklistedWordsDatabase = new BufferedReader(
new InputStreamReader(
resource,
StandardCharsets.UTF_8
)
).lines()
.collect(Collectors.toList());
}