文章目录

  • ​​1、问题描述​​
  • ​​2、结果显示​​
  • ​​3、具体代码​​
  • ​​3.1 文件写入​​
  • ​​3.2 文件读取​​

1、问题描述

使用opencFileOutput写入文件,使用openFileInput读取文件。

2、结果显示

点击写入文件将解析过的xml文件信息写入到某个文件中。

使用文件读取将文件中的信息保存到字符串中。

使用AlertDialog展示在屏幕上。

Android读写文件_android

3、具体代码

3.1 文件写入

private void writeFile(){
FileOutputStream fos = null; //声明一个FileOutputStream对象
try{
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE); //以MPRIVATE模式打开文件名为FILE_NAME的文件。
if(!msg.isEmpty()){ //这里的msg是已经解析好的xml文件,并将解析好的xml文件保存在msg
fos.write(msg.getBytes()); //将msg写入到FILE_NAME中
Toast.makeText(MainActivity.this,"File was written successfully!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Fail!",Toast.LENGTH_LONG).show();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
CloseOutputStream(fos); //关闭文件

}
private void CloseOutputStream(FileOutputStream fos) {
if (fos != null){
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

3.2 文件读取

private String readFile(){
FileInputStream fis = null; /声明一个FileInPutStream对象
String text="";
try{
fis = openFileInput(FILE_NAME); //获取FILE_NAME文件内容
if(fis.available() == 0){ //如果什么都没获取到就返回空字符串
return "";
}
byte[] readBytes = new byte[fis.available()]; //将获取数据以二进制方式保存到数组中
fis.read(readBytes); //这句不加就不能正常读取,我认为这句是将转为二进制的信息解码
text = new String(readBytes,"utf-8"); //转化为utf8类型字符串

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
CloseInputStream(fis);
return text;
}

private void CloseInputStream(FileInputStream fis) {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}