.crt文件上的FileNotFoundException

时间:2017-03-22 05:15:26

标签: java android filenotfoundexception

我正在尝试加载文件,即使文件存在,我也会收到FileNotFoundException。假设Android在项目级别启动,我尝试了绝对路径(C:/Users/cdeck_000/AndroidStudioProjects/ProjectCaligula_Final/cert/cert.crt)和相对路径(cert / cert.crt)。当我使用相对路径运行它并请求文件绝对路径时,我得到了这个:

路径:/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

File Structure

如果我对Android的绝对/相对路径的知识错误或者给我如何解决这个问题的建议,那么有人可以加入并告诉我吗?我已经认为权限是问题,但我提出了文件权限(相当于chmod 777)并且它没有改变任何东西。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

  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
                    }
                }
            }