Android open failed: ENOENT (No such file or directory)

问题描述:

Android open failed: ENOENT (No such file or directory)

原因:

    应用在sdcard中缓存文件的时候,如果文件夹被不小心删除,往该文件写入数据的时候,由于没有找到路径,所以报错。最主要是因为FileOutputStream创建一个流文件路径时或者是对一个File文件路径直接操作时,没有捕获异常。

解决方式:

(1)检查是否有加入权限,如果没有加首先加上。

<user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

(2)检查创建文件的时候是否有添加try...catch(),如果没有请加上,示例如下所示:

没加之前的代码:

public static void makeRootDirectory(String filePath) {

File file =file =newFile(filePath);

if(!file.exists()) {

file.mkdir();

}}


修改过后的代码:

public static void makeRootDirectory(String filePath) {

File file =null;

try{

file =newFile(filePath);

if(!file.exists()) {

file.mkdir();}

}catch(Exception e) {}}



(3)如果加上了try...catch()仍然报错,请检查路径时候包含目录,如:目录+a.txt;示例如下:

没加之前的代码:

private BufferedOutputStream createOutputStream(Context context, String name)

throws FileNotFoundException {

File file = null;

try {

//这里的getWorkDirManager.getPath()表示一个目录的路径,name表示该目录下的一个文件

file = new File(getWorkDirManager().getPath() + "/" + name);

} catch (Exception e) {

log.d("exception="+e.toString());

}// true表示已追加的方式写入文件,false表示已覆盖的方式写入文件,解决同一个份内容写入多次的问题

FileOutputStream fileOutputStream = new FileOutputStream(file, false);

return new BufferedOutputStream(fileOutputStream);}


修改后的代码:

private BufferedOutputStream createOutputStream(Context context, String name)

throws FileNotFoundException {

File file = null;

File fileDir=null;

try {

fileDir=new File(getWorkDirManager().getPath());

if(!fileDir.exists()){

fileDir.mkdir();

}

file = new File(getWorkDirManager().getPath() + "/" + name);

} catch (Exception e) {

}

log.d("exception="+e.toString());

}

// true表示已追加的方式写入文件,false表示已覆盖的方式写入文件,解决同一个份内容写入多次的问题

FileOutputStream fileOutputStream = new FileOutputStream(file, false);

return new BufferedOutputStream(fileOutputStream);

}



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容