android读写删file,安卓文件存储/文件读写操作

安卓存储位置通常有两大类,一类是用户随意指定,这个需要配置权限,高版本安卓中还需要用代码获得权限,这种存储在 APP 卸载后,不会随之删除。

另一类存储是存储在特定的位置,并不需要在 AndroidManifest.xml 中配置权限,在 APP 卸载后,或者用户清除该 APP 的数据后,这些存储文件都会被删除。

本文讲的第二类。

一、如何获得这类目录的路径

使用 getFilesDir()、getCacheDir(),以 getFilesDir() 为例,这个目录是类似:/data/data/com.itpow.test/files

二、读取这个目录下有哪些文件

示例,选取以 itpow 开头的文件。File file = new File(getFilesDir().getPath());

File[] fs = file.listFiles(new FileFilter() {

@Override

public boolean accept(File pathname) {

if (pathname.getName().startsWith("itpow")) {

return true;

}

else {

return false;

}

}

});

三、读取某一文件的内容

使用 FileInputStream,注意,Input 是读。try {

FileInputStream fis = openFileInput(f.getName());

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

String s = new String(buffer);

fis.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

四、写入某一文件

使用 FileOutputStream,注意 Output 是写。try {

FileOutputStream fos = openFileOutput(filePath, MODE_PRIVATE);

fos.write(s);

fos.close();

} catch (FileNotFoundException e) {

result = false;

e.printStackTrace();

} catch (IOException e) {

result = false;

e.printStackTrace();

}

五、删除文件File f = new File(getFilesDir().getPath() + "/" + fileName);

f.delete();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值