我在目录中有 json 文件:C:\Users\pim\Documents\triage\src\test\resources\jsons
并且我有返回 File[] 的方法:
public static File[] listFiles() throws IOException {
File dir = new File("src/test/resources/jsons");
if (dir.isFile()) {
throw new IllegalArgumentException(dirString);
}
Path folderPath = dir.toPath().toAbsolutePath();
List<File> files = new LinkedList<File>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(folderPath)) {
for (Path path : directoryStream) {
if (path.toString().endsWith(".json")) {
File file = new File(path.toString());
if (file != null) {
files.add(file);
}
}
}
} catch (IOException ex) {
System.err.println("Error reading files");
ex.printStackTrace();
}
return files.stream().toArray(File[]::new);
}
它在 Eclipse 上正确运行,但是当我从 bash 作为 jar 运行它时它返回:
<块引用>NoSuchFileException: C:\Users\pim\Documents\triage\target\src\test\resources\jsons
为什么会出现在这个路径中:
C:\Users\pim\Documents\triage\target\src\test\resources\jsons
而不是这个:
C:\Users\pim\Documents\triage\src\test\resources\jsons
怎么改?看起来路径随 jar 位置而变化。
那些json在构建后位于目标文件夹中:
C:\Users\pim\Documents\triage\target\test-classes\jsons
仅当应用程序由 jar 运行时,如何指向这个 jar 以在其相对路径中查找?