Android文件读写

来源:互联网 发布:nginx 限制ip访问目录 编辑:程序博客网 时间:2024/06/05 21:14


一、Android的文件操作

文件的操作模式有4种:
1.Context.MODE_PRIVATE
默认操作模式,代表文件是私有数据,只能够被本应用自身访问,写入内容会覆盖原文件内容。
2.Context.MODE_APPEND
会检验文件是否存在,不存在的话会创建新文件,存在的话就往文件中追加内容。
3.Context.MODE_WORLD_READABLE
当前文件可以被其他应用读取
4.Context.MODE_WORLD_WRITEABLE
当前文件可以被其他应用写入
后面两个是控制其他应用是否有读写权限的。
如果又要读又要写:
openFileOutput("xxx", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);

openFileOutput(name, mode)
打开问价能输出流,往文件中写入数据
openFileInput(name)
打开文件输入流,就是读取文件中的信息
getDir(name, mode); 
在data目录下获取或者创建name的子目录
getFilesDir(); 
获得data目录下file的绝对路径
deleteFile(name)
删除data目录下的指定文件
fileList()
返回data目录下的全部文件

因为Andoid的内核是Linux内核,有着与Linux一样的文件安全访问方式,每一个应用都有自己的用户ID(userid),访问其他目录时,需要匹配用户ID(userid),所以要想其他应用可以访问,创建文件时需要设置特定的模式(mode)。

我们生成的文件在data/data/应用包名/file目录下

一、文件写入:openFileOutput(name, mode),接着把数据写入文件
try {
   FileOutputStream fos = openFileOutput("xxxx", Context.MODE_APPEND);
   fos.write("".getBytes());
   fos.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
二、文件读取:openFileInput(name),读取文件中的数据
try {
   FileInputStream  fis = openFileInput("xxx");
   byte[] b = new byte[1024];
   StringBuffer sb = new StringBuffer();
   
   int len = 0;
   while((len = fis.read(b))>0){
    sb.append(new String(b,0,len));
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }


1 0
原创粉丝点击