FileOutputSteam正确使用方式

 首先要知道,FileOutputSteam 是不会创建不存在的路径,所以需要先创建路径,再创建文件

File photoFileDir = new File(Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/");  
// 注意path参数,最后是有斜杠的
if(!photoFileDir.exists()){    // 如果路径不存在,就创建路径
     photoFileDir.mkdirs();  
}
// mkdir()是创建单级目录,必须在已存在的目录下创建目录
// mkdirs()是创建多级目录,比如不存在ClipHeadPhoto目录,就先创建该目录,再创建cache目录
File photoFile = new File(photoFileDir, photoName);
// 然后再创建路径和文件名的File对象
FileOutputStream fileOutputStream = null;
try {
    fileOutputStream = new FileOutputStream(photoFile);
    // XXXXX 各种操作    
} catch (Exception e) {
    photoFile.delete();    // 如果抛出异常,一定要删除该文件
    e.printStackTrace();
} finally {
    try {
        fileOutputStream.close();    // finally中,一定要关闭输出流
    } catch (Exception e) {
        e.printStackTrace();
    }
}
// 注意处理异常的方式,非常重要

猜你喜欢

转载自blog.csdn.net/weixin_37946518/article/details/81302817
今日推荐