[英]How to get Java File absolute path from InputStream?
I'm on Java 6 and I have a method that scans the runtime classpath for a file called config.xml
. 我在Java 6上,我有一个方法,它扫描运行时类路径中的一个名为
config.xml
的文件。 If found, I would like to read the contents of the file into a string: 如果找到,我想将文件的内容读成字符串:
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());
}
}
When I run this code, I get the following console output: 当我运行此代码时,我得到以下控制台输出:
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
So the classpath scan for config.xml
is successful, but then the reader can't seem to find the file. 所以
config.xml
的类路径扫描是成功的,但是读者似乎无法找到该文件。 Why??? 为什么??? My only theory is that when
config.xml
is found on the classpath, it doesn't contain an absolute path to the location of the file on the file system, and perhaps that's what the reader code is looking for. 我唯一的理论是,当在类路径中找到
config.xml
时,它不包含文件系统上文件位置的绝对路径,也许这就是读者代码所寻找的内容。
You use a resource from a classloader. 您使用类加载器中的资源。
Instead of doing: 而不是做:
InputStream istream = this.getClass().getClassLoader().getResourceAsStream("config.xml");
do: 做:
URL url = getClass().getResource("config.xml");
That URL will have the path (use .toURI().getPath()
). 该URL将具有路径(使用
.toURI().getPath()
)。 To open the matching input stream afterwards, use .openStream()
. 要在之后打开匹配的输入流,请使用
.openStream()
。
You know at least that the resource exists: if it doesn't, .getResource{,AsStream}()
both return null
(instead of throwing an IOException, which is doubtful imho) 您至少知道资源存在:如果不存在,
.getResource{,AsStream}()
都返回null
(而不是抛出IOException,这是可疑的imho)
From your given example, it is not clear what fileName
refers to. 从您给出的示例中,不清楚
fileName
引用的是什么。 You should just use the stream you got from getResourceAsStream()
to read you file, something along 你应该只使用你从
getResourceAsStream()
获得的流来读取你的文件
reader = new BufferedReader(new InputStreamReader(istream));
And you should avoid to repeatedly allocating buf
new for every read cycle, once is enough. 并且你应该避免在每个读取周期重复分配
buf
new,一旦足够。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.