Java - 带有Classpath的java.io.File

问题描述 投票:1回答:1

我需要使用/定义一个java.io.File变量类型来获取一个文件,该文件将作为参数发送到另一个方法。

现在我有相对路径:

File file = new File("C:/javaproject/src/main/resources/demo/test.txt");

我想用ClassLoader这样改变它:

ClassLoader.getSystemResource("/demo/test.txt");

但我不能将它用于File,因为它不是同一类型。如果我使用.toString()它返回NullPointerException:

java.lang.NullPointerException: null

当我用System输出打印它时返回相同的,异常:System.out.println(ClassLoader.getSystemResource(“demo / test.txt”)。toString());

文件夹和文件都存在。为什么会出错?

java file nullpointerexception classpath
1个回答
2
投票

你可以这样做:

try {
    URL resource = getClass().getClassLoader().getResource("demo/test.txt");
    if (nonNull(resource)) {
        File file = new File(resource.toURI());
        // do something
    }
} catch (URISyntaxException e) {
    LOGGER.error("Error while reading file", e);
}

这个answer显示了ClassLoader.getSystemResourcegetClassLoader().getResource()之间的不同

© www.soinside.com 2019 - 2024. All rights reserved.