.crt 文件上的 FileNotFoundException

FileNotFoundException on .crt file

我正在尝试加载一个文件,但我收到一个 FileNotFoundException,即使该文件存在。我已经尝试过绝对路径 (C:/Users/cdeck_000/AndroidStudioProjects/ProjectCaligula_Final/cert/cert.crt) 和相对路径 (cert/cert.crt),假设 Android 从项目级别开始。当我 运行 它使用相对路径并询问文件绝对路径时,我得到这个:

路径:/cert/cert.crt

下面是代码和项目结构。

File file = new File("cert/cert.crt");
boolean i = file.exists();  //false
boolean r = file.canRead(); //false
String path = file.getAbsolutePath(); //cert/cert.crt
String pathForApp = new File(".").getAbsolutePath(); //returns "/."
InputStream caInput = new BufferedInputStream(new FileInputStream(file)); //error

如果我对 absolute/relative 路径和 Android 的了解有误,谁能插话告诉我,或者给我建议如何解决这个问题?我已经认为权限是问题所在,但我提高了文件权限(相当于 chmod 777)并且没有任何改变。

我遇到了与我使用以下方式解决问题相同的问题

  1. 创建assets文件夹
  2. 将文件复制到 assets 文件夹
  3. assets
  4. 读取文件

使用下面的代码从 assets 文件夹中读取

BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(getAssets().open("cert.crt")));

            // do reading, usually loop until end of file reading
            String mLine;
            while ((mLine = reader.readLine()) != null) {
                //process line

            }
        } catch (IOException e) {
            //log the exception
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //log the exception
                }
            }
        }

您应该将其放入 src/cert/cert.crt,这使它成为资源,而不是文件,因此您应该使用 Class.getResourceAsStream("/cert/cert.crt"),而不是 new FileInputStream()