设置文件生成的权限:
public static boolean saveInfo(
Context context, String userName, String userPass, int mode){
try {
FileOutputStream fos;
switch (mode) {
case 0:
fos = context.openFileOutput(
"private.txt", Context.MODE_PRIVATE);
fos.write((userName+"##"+userPass).getBytes());
fos.close();
break;
case 1:
fos = context.openFileOutput(
"readable.txt", Context.MODE_WORLD_READABLE);
fos.write((userName+"##"+userPass).getBytes());
fos.close();
break;
case 2:
fos = context.openFileOutput(
"writeable.txt", Context.MODE_WORLD_WRITEABLE);
fos.write((userName+"##"+userPass).getBytes());
fos.close();
break;
case 3:
fos = context.openFileOutput(
"public.txt", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
fos.write((userName+"##"+userPass).getBytes());
fos.close();
break;
default:
break;
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
下面是读取文件和写入文件的程序代码:
读取文件:
public void readInfo(View view){
File file = new File("/data/data/com.aaron.login/files/public.txt");
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String result = br.readLine();
Toast.makeText(MainActivity.this,
result,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this,
"读取文件失败",
Toast.LENGTH_LONG).show();
}
}
写入文件:
public void writeInfo(View view){
File file = new File("/data/data/com.aaron.login/files/public.txt");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write("hahaha".getBytes());
fos.close();
Toast.makeText(MainActivity.this,
"写入文件成功",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this,
"写入文件失败",
Toast.LENGTH_LONG).show();
}
}