Context 提供两个方法来打开应用程序的数据文件夹里的文件IO流体系。
FileInputStream openFileInput(String name):打开应用程序的数据文件夹下的name文件对应的输入流
FileOutputStream openFileOutput(String name,int mode):
打开应用程序的数据文件夹下的name文件对应的输出流
其中:
mode 有如下几个值:
(1)MODE_PRIVATE :该文件只能被当前程序所读写
(2)MODE_APPEND :以追加的方式打开文件,应用程序可以向该文件中追加内容
(3)MODE_WORLD_READABLE : 该文件的内容可以被其他程序读取
(4)MODE_WORLE_WRITEABLE : 该文件的内容可由其他程序读写
除此之外,Context还提供了如下几个方法来访问应用程序的数据文件夹:
File getFilesDir():获取应用程序的数据文件夹下的据对路径
String[] fileList(): 返回应用程序的数据文件夹下的全部文件
deleteFile(String):删除应用程序的数据文件夹下的指定文件
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String PATH = "a.txt";
private Button mBtnRead;
private Button mBtnWrite;
private TextView mTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
mTv = findViewById(R.id.tv);
mBtnRead = findViewById(R.id.btn_read);
mBtnWrite = findViewById(R.id.btn_write);
mBtnWrite.setOnClickListener(this);
mBtnRead.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_read:
mTv.setText(read()+getFilesDir());//getFilesDir:得到应用程序的数据文件夹的路径
break;
case R.id.btn_write:
write("你好,大傻子");
break;
default:
break;
}
}
/**
* 写文件
*/
private void write(String content){
try {
Log.d("TAG", "write: ");
//以追加的方式打开文件输入流
FileOutputStream outputStream = openFileOutput(PATH, Context.MODE_APPEND);
//将FileOutPutStream包装成printStream
PrintStream ps = new PrintStream(outputStream);
//输出文件内容
ps.println(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 读文件
*/
private String read(){
try {
//打开文件输入流
FileInputStream inputStream = openFileInput(PATH);
byte[] buff = new byte[1024];
int hasRead = 0;
StringBuffer sb = new StringBuffer("");
//读取文件
while ((hasRead = inputStream.read(buff)) > 0){
//StringBuilder 的append方法,将string追加到StringBuilder 中
sb.append(new String(buff,0,hasRead));
}
return sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}