【问题标题】:Reading a file from Raw folder is giving File not found exception从 Raw 文件夹中读取文件会导致 File not found 异常
【发布时间】:2019-06-19 06:47:26
【问题描述】:

我正在尝试从 Raw 文件夹中读取文件 dev.txt

我已放置文件:


Uri uri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator + CaringApp.getAppInstance().getPackageName() + "/raw/" + "dev.txt");
PEMParser pemParser = new PEMParser(new FileReader(uri.getPath()));

我遇到了异常:

java.io.FileNotFoundException: /com.appname.organizer/raw/dev: open failed: ENOENT (No such file or directory)

在线:

PEMParser pemParser = new PEMParser(new FileReader(uri.getPath()));

【问题讨论】:

标签: android


【解决方案1】:

我正在尝试从 Raw 文件夹中读取文件 dev.txt

这是您的开发机器上的一个文件。它不是 Android 设备上的文件。 FileReader 将不起作用。

相反,在Resources 对象上使用openRawResource() 以获取InputStream。如果需要,请将其包装在 InputStreamReader 中。

【讨论】:

    【解决方案2】:

    在我的应用程序中,我使用了它并且它对我有用:

    URL url = getClass().getResource("/assets/dev.txt");
    File f = new File(url.toURI());
    

    或者您可以直接使用 getResourceAsStream() 方法获取输入流:

    InputStream  is= getClass().getResourceAsStream("/assets/levels.txt");
    isr = new InputStreamReader(is);
    

    【讨论】:

      【解决方案3】:

      尝试删除文件名的扩展名。例如。 "dev" 不是 "dev.txt" 喜欢:

      Uri uri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator + CaringApp.getAppInstance().getPackageName() + "/raw/" + "dev");
      

      【讨论】:

        【解决方案4】:

        我正在使用此函数将二进制文件从原始目录复制到应用程序文件目录,然后从那里执行二进制文件。

            File dev = new File(getApplicationContext().getFilesDir(), "dev.txt");
        
                if (!dev.exists()) {
                    try {
                        dev.createNewFile();
                    } catch (IOException e) {
                        Log.e(TAG, "Failed to create new file!", e);
                    }
                installBinaryFromRaw(this, R.raw.dev, dev);   
        

        函数将文件从 raw 复制到 /data/data//file/filename

            public static void installBinaryFromRaw(Context context, int resId, File file) {
                final InputStream rawStream = context.getResources().openRawResource(resId);
                final OutputStream binStream = getFileOutputStream(file);
        
                if (rawStream != null && binStream != null) {
                    pipeStreams(rawStream, binStream);
        
                    try {
                        rawStream.close();
                        binStream.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Failed to close streams!", e);
                    }
        
                    doChmod(file, 755);
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-11
          • 2015-02-08
          • 1970-01-01
          • 2017-02-09
          • 2014-10-05
          • 2013-01-04
          • 2017-09-22
          • 1970-01-01
          相关资源
          最近更新 更多