简体   繁体   English

如何从InputStream获取Java File绝对路径?

[英]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.

相关问题 从 InputStream(ByteArrayInputStream) 对象获取绝对文件路径 - Get the absolute file path from InputStream(ByteArrayInputStream) object JAVA项目中如何获取文件绝对路径 - How to get the file absolute path in JAVA project 如何在java中获取文件绝对路径 - How to get file Absolute path in java Selenium-Java:如何获取文件的绝对路径 - Selenium - Java: How to get absolute path to the file 如何使用Java applet获取绝对文件路径 - How to get an absolute file path with a Java applet 如何获取.java文件的绝对物理路径? - How to get absolute physical path of .java file? 如何在 Java Rest API 中获取真实路径 InputStream 文件 - How to get real path InputStream file in Java Rest API 如何获取具有绝对路径的文件的InputStream并将其添加到StreamedContent对象,以便在ap:fileDownload中使用它? - How to get the InputStream of a file that has an absolute path and add it to a StreamedContent object in order to use it in a p:fileDownload? 如何在Java中获取绝对路径 - How to get the absolute path in Java Java - 如何从绝对路径获取文件名并删除其文件扩展名? - Java - How to get the name of a file from the absolute path and remove its file extension?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM