Android 文件操作之openFileOutput

时间:2023-03-09 21:24:20
Android 文件操作之openFileOutput

  openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 会自动创建它。创建的文件保存在/data/data/<package name>/files目录。

  openFileOutput()方法的第二参数用于指定操作模式,有四种模式,分别为:

    Context.MODE_PRIVATE    = 0
    Context.MODE_APPEND    =  32768
    Context.MODE_WORLD_READABLE =  1
    Context.MODE_WORLD_WRITEABLE =  2

  Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中,可以使用Context.MODE_APPEND。
  Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
  Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
  MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

如果希望文件被其他应用读和写,可以传入:
openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

(1):判读文件是否存在

public boolean existsFile(String fileName){
     String path = this.getFilesDir().getPath()+"//";
File file = new File(path+fileName);
if(file.exists()){
return true;
}
return false;
}

(2):读取文件

public String readFile(String fileName) throws IOException{
FileInputStream fis = context.openFileInput(fileName);
int len = fis.available();
byte []buffer = new byte[len];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((fis.read(buffer))!=-1){
baos.write(buffer);
}
byte []data = baos.toByteArray();
baos.close();
fis.close();
return new String(data);
}

(3):保存文件

public void saveFile(String fileName, String str) throws IOException{
FileOutputStream fos = context.openFileOutput(fileName, Activity.MODE_APPEND);
byte[]bytes=str.getBytes();
fos.write(bytes);
fos.flush();
fos.close();
}