【问题标题】:An error when trying to copy a file from the assets folder尝试从资产文件夹复制文件时出错
【发布时间】:2023-04-03 01:05:02
【问题描述】:

我正在尝试将文件从资产文件夹复制到外部存储,这是我拥有的代码:

File f=new File(Environment.getExternalStorageDirectory(), "imgs/" + str2);
        if (!f.exists()) {
            try {
                InputStream ins = getApplicationContext().getAssets().open("imgs/" + str2);
                FileOutputStream out=new FileOutputStream(f);
                byte[] buf=new byte[1024];
                int len;
                while ((len=ins.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                ins.close();
                out.close();
            }
            catch (IOException e) {
                Log.e("FileProvider", "Exception copying from assets", e);
            }
        }

但我得到的错误是: java.io.FileNotFoundException: /storage/emulated/0/imgs/pic_name.jpg (No such file or directory)

但是,我正在创建这个文件,所以我不知道为什么它说它没有找到。

【问题讨论】:

  • 请找出引发异常的代码行并发布完整的堆栈跟踪。
  • 除了 Amrnoid 关于创建目录的观点之外,如果您还没有这样做,您还需要请求WRITE_EXTERNAL_STORAGE 权限(包括运行时请求)。

标签: android file assets


【解决方案1】:

因为“img”目录不存在,所以必须创建目录

代码:

   String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/imgs/";
        File file=new File(rootPath);
      if(!file.exists()){
         file.mkdirs();
       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2013-06-04
    • 2014-05-04
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2017-09-20
    相关资源
    最近更新 更多