文前声明:转载时注明文章出处。
http://blog.youkuaiyun.com/dinglin_87/article/details/7433541
本文重点展示,对/data/data/<package name>/files中文件的读写操作的实现。
一、写出数据到files文件夹中,Activity提供了openFileOutput()方法,可以把数据输出到/data/data/<package name>/files的文件夹中。
- public class FileActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- ...
- FileOutputStream outStream = this.openFileOutput("itcast.txt", Context.MODE_PRIVATE);
- outStream.write("测试".getBytes());
- outStream.close();
- }
- }
第一个参数:指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 自动创建它。保存在/data/data/<package name>/files目录中,如: /data/data/cn.itcast.action/files/ceshi.txt 。
第二参数用于指定操作模式,有四种模式,分别为:
- Context.MODE_PRIVATE
- Context.MODE_APPEND
- Context.MODE_WORLD_READABLE
- Context.MODE_WORLD_WRITEABLE
可以同时传入一种以上的模式如:
- openFileOutput("ceshi.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
二、读取 /data/data/<package name>/files/ceshi.txt中的数据。直接上代码:
- FileInputStream inStream = context.openFileInput(ceshi.txt);//只需传文件名
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();//输出到内存
- int len=0;
- byte[] buffer = new byte[1024];
- while((len=inStream.read(buffer))!=-1){
- outStream.write(buffer, 0, len);//
- }
- byte[] content_byte = outStream.toByteArray();
- String content = new String(content_byte);
- system.out.println(content)
总结:重点注意的地方就是openFileOutput()的第一个参数和openFileInput()的参数,不需要写绝对路径,只需写文件名就可以了!
附言:当然读取数据时也可以用绝对路径,没有本文所述的方便,比如读取文件时可以用:
- Context context=MainActivity.this;//首先,在Activity里获取context
- File file=context.getFilesDir();
- String path=file.getAbsolutePath();
- System.out.println(path);
- File file = new File(path+ceshi.txt);
- FileInputStream inStream = new FileInputStream(file);//需传路径: /data/data/cn.itheima.rw_file/files/ceshi.txt
上边几行的代码的作用仅仅相当于下边这一句代码的作用:
- context.openFileInput("ceshi.txt";
何苦呢!你说呢!