如何从输入流中获取Java文件绝对路径?
2022-09-02 19:55:07
						我使用的是 Java 6,我有一个方法可以扫描运行时类路径以查找名为 .如果找到,我想将文件的内容读入字符串:config.xml
InputStream istream = this.getClass().getClassLoader().getResourceAsStream("config.xml");
if(istream != null) {
    System.out.println("Found config.xml!");
    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(fileName));
        char[] buf = new char[1024];
        int numRead = 0;
        while((numRead=reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
            reader.close();
        }
    } catch (FileNotFoundException fnfExc) {
        throw new RuntimeException("FileNotFoundException: " + fnfExc.getMessage());
    } catch (IOException ioExc) {
        throw new RuntimeException("IOException: " + ioExc.getMessage());
    }
}
当我运行此代码时,我得到以下控制台输出:
Found config.xml!
Exception in thread "main" java.lang.RuntimeException: FileNotFoundException: config.xml (No such file or directory)
    at com.me.myapp.Configurator.readConfigFileFromClasspath(Configurator.java:556)
    at com.me.myapp.Configurator.<init>(Configurator.java:34)
    ...rest of stack trace omitted for brevity
因此,类路径扫描成功,但随后读者似乎找不到该文件。为什么???我唯一的理论是,当在类路径上找到它时,它不包含文件系统上文件位置的绝对路径,也许这就是读者代码正在寻找的。config.xmlconfig.xml