• FileOutputStream报错"File not Found" (Android)


    问题描述:  

      使用FileOutputStream,根据文档上看,new FileOutputStream(path),如果path路径下的文件不存在,则自动创建新的文件。

      但是在使用过程中,

    path = Environment.getExternalStorageDirectory().getPath() + "/document/mine/www/te.text";

      此时new一个FileOutputStream,会报“File not found”的异常。

    问题分析:

      修改path路径,  

    path = Environment.getExternalStorageDirectory().getPath() + "/document/te.text";

      此时再new新的outputstream对象,可正常编译。

      导致前面提到的异常的原因是,文件目录层级过深。

    解决方案:

      自己创建不存在的目录路径。

      在目录层级大于2时(如“/document/mine/te.text"),mkdirs()方法执行时会返回false。

      此处使用拼接的方法,将目录分段进行创建(如将path分为"/document/mine"和”/www/text"),这样便可以避免以上问题,实例代码如下

    copyAssetsToSd(context, Environment.getExternalStorageDirectory().getPath() + File.separator + "document",
                    "mine" + File.separator + "cordova.js");
    
    private static void copySingleAssetToSd(Context context, String sdPath, String assetPath) {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                File dirFile = new File(sdPath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs(); // 第一段
                }
                File file = new File(sdPath + File.separator + assetPath);
                if (!file.getParentFile().exists()) {
                    // 分两次mkdirs,是为了避免目录层级过高导致目录创建失败的情况
                    file.getParentFile().mkdirs();
                }
                if (!file.exists()) {
                    file.createNewFile();
                }
                outputStream = new FileOutputStream(file); // 创建实例
                inputStream = context.getAssets().open(assetPath);
                byte[] buffer = new byte[1024];
                int length = inputStream.read(buffer);
                while (length > 0) {
                    outputStream.write(buffer, 0, length);
                    length = inputStream.read(buffer);
                }
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != inputStream) {
                        inputStream.close();
                    }
                    if (null != outputStream) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
  • 相关阅读:
    【LeetCode】152. 乘积最大子数组(DP)
    【剑指Offer】49. 丑数(三指针)
    [P1979][NOIP2013] 华容道 (BFS建图+SPFA)
    [P1850][NOIP2016] 换教室 (期望+DP+Floyd)
    差分约束学习笔记
    [P1291][SHOI2002] 百事世界杯之旅 (期望)
    [P4342][IOI1998] Polygon (区间DP)
    [P3802] 小魔女帕琪 (期望)
    [P1273] 有线电视网 (树形DP+分组背包)
    树链剖分学习
  • 原文地址:https://www.cnblogs.com/ivan-aldrich/p/4681945.html
Copyright © 2020-2023  润新知