FileInputStream:没有这样的文件或目录

时间:2018-01-10 09:46:21

标签: java

效果很好"新的FileInputStream(f.getAbsoluteFile())"

private byte[] loadFile(String path) throws IOException {
    File f = new File("./build/classes/" + path);
    try (InputStream is = new FileInputStream(f.getAbsoluteFile())) {
        byte[] data = loadFile(is);
        return data;
    }
}

" new FileInputStream(f)"

private byte[] loadFile(String path) throws IOException {
    File f = new File("./build/classes/" + path);
    try (InputStream is = new FileInputStream(f)) {
        byte[] data = loadFile(is);
        return data;
    }
}

抛出异常:

java.io.FileNotFoundException: ./build/classes/traces/onmethod/ErrorDuration.class (No such file or directory)

at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)

我无法想象为什么。

1 个答案:

答案 0 :(得分:0)

首先确保从同一工作目录运行两个程序。

此外,在第一种情况下,您的路径首先被解析为绝对路径。 例如:/opt/local/myprod/bin/build/classes/traces/onmethod/ErrorDuration.class

Whle FileInputStream使用文件的“简单路径”(File.getPath())

根据您当前的工作目录,您的权限和符号链接,这两条路径可能意味着两件事。

从您运行程序的目录中 - 此路径是否有效?

ls ./build/classes/traces/onmethod/ErrorDuration.class

另见: What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?