我在 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.xml
成功,但是阅读器似乎找不到文件。为什么???我唯一的理论是,当config.xml
在类路径中找到时,它不包含文件系统上文件位置的绝对路径,也许这就是阅读器代码正在寻找的。