Android openFileInput 和 openFileOutput 写入文件和读写文件

写入和读写的文件位置:
在/data/data/<包名>/files


应用功能

输入数据然后点击 写入按钮 存储,然后再 点击 读取按钮 读取出来
(布局界面未写)


具体代码

MainActivity.java

写入数据到文件

     FileOutputStream fos =  openFileOutput(filename, Activity.MODE_APPEND);   //打开文件输出   filename :自己的文件名 如info.txt
     OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
     osw.write(data); //data自己要写的数据
     fos.flush();
     osw.flush();
     osw.close();
     fos.close();

从文件读取数据

   FileInputStream fis =  openFileInput(filename);
   InputStreamReader isr = new InputStreamReader(fis,"utf-8");//字节流转为字符流
   char input[] = new char[fis.available()];         //  有效的文本长度
   int contentLength =  isr.read(input) ;  //contentLength = 读取到的是字符的长度 一个汉字,算一个字符,一个英文字母算一个字符
   isr.close();
   fis.close();
   String content = new String(input);   //  content 是读取到的内容

代码讲解

Activity.MODE_APPEND //是添加内容
Activity.MODE_PRIVATE //是将原来内容删除再添加
具体参考:https://www.cnblogs.com/yshyee/archive/2013/12/14/3474033.html

猜你喜欢

转载自blog.csdn.net/qq_38340601/article/details/81776088