有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java InputStream找不到文件

我正在尝试使用InputStream打开一个YAML文件,以便在SnakeYAML上使用。 尽管我遇到了一个问题,但文件始终为空,无论我尝试了什么,下面是我的代码:

this.configFile = new File("config.yml");
this.yaml = new Yaml();

if (!configFile.exists()) {
    try {
        configFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

InputStream inputStream = this.getClass()
        .getClassLoader()
        .getResourceAsStream(configFile.getName());

Map<String, Object> obj = yaml.load(inputStream);
System.out.println(obj);

我尝试直接键入“config.yml”而不是“configFile.getName()”,我甚至尝试了System.getProperty("user.dir") + configFile.getName(),但它总是返回null并给出错误org.yaml.snakeyaml.error.YAMLException: java.io.IOException: Stream closed

我确信该文件存在,因为我可以查看和编辑它,并且它位于项目文件夹中,我似乎无法访问它
enter image description hereenter image description here


共 (1) 个答案

  1. # 1 楼答案

    使用System.getProperty("user.dir")时,需要添加'/'来指定正确的路径

    所以,也许你得写

    System.getProperty("user.dir") + "/" + configFile.getName()