在 java 中打开具有绝对路径的文件

Open file with absolute path in java

我写这段代码是为了将文件内容读取到字节数组中。 当 path (在构造函数中给出)是相对的时,它工作正常。但我希望它能以绝对路径工作。我在 java File class 文档中查找但感到困惑。如何更改它以使用绝对路径?

        File file = new File(path);
        byte[] bytesArray = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytesArray);
        fis.close();

在您的代码中;

File file = new File(path);

您的 path 字符串变量只需要是绝对的而不是相对的。

我不明白为什么它不起作用。您是否尝试将路径变量更新为文件的绝对路径?