首页 > 解决方案 > 从 InputStream(ByteArrayInputStream) 对象中获取绝对文件路径

问题描述

我有以下代码:

class Train{
   static{
        InputStream inpStr = Train.class.getClassLoader().getResourceAsStream("ABC.properties");
        Properties props = new Properties();
        props.load(inpStr);
   }
}

我想知道这个文件 ABC.properties 的绝对文件路径,即 inpStr 从哪里读取它?通过调试,我意识到分配给 inpStr 的对象实际上是java.io.ByteArrayInputStream. 但是我找不到获取绝对文件路径的方法。请帮忙

标签: javaclasspathinputstreambytearrayinputstream

解决方案


First you need to get resource, not resourceAsStream:

URL resource = Train.class.getClassLoader().getResource("ABC.properties");

Then you get the path

Path path = Paths.get(resource.toURI());

And finally you can display the absolutePath

System.out.println(path.toAbsolutePath().toString());

推荐阅读