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();

            }

        }

    }

 

你可能感兴趣的:(FileOutputStream报错"File not Found" (Android))