android中对/data/data/<package name>/files下文件的读写操作

原文:http://blog.csdn.net/dinglin_87/article/details/7433541


本文重点展示,对/data/data/<package name>/files中文件的读写操作的实现。

       一、写出数据到files文件夹中,Activity提供了openFileOutput()方法,可以把数据输出到/data/data/<package name>/files的文件夹中。

[java]  view plain copy
  1. public class FileActivity extends Activity {  
  2.     @Override   
  3.   
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         ...   
  6.     FileOutputStream outStream = this.openFileOutput("itcast.txt", Context.MODE_PRIVATE);  
  7.         outStream.write("测试".getBytes());  
  8.         outStream.close();     
  9.     }  
  10. }  


      第一个参数:指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 自动创建它。保存在/data/data/<package name>/files目录中,如: /data/data/cn.itcast.action/files/ceshi.txt 。
      第二参数用于指定操作模式,有四种模式,分别为:

[html]  view plain copy
  1. Context.MODE_PRIVATE  
  2.        Context.MODE_APPEND  
  3.        Context.MODE_WORLD_READABLE  
  4.        Context.MODE_WORLD_WRITEABLE  

     可以同时传入一种以上的模式如:

[html]  view plain copy
  1. openFileOutput("ceshi.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);  


二、读取 /data/data/<package name>/files/ceshi.txt中的数据。直接上代码:

[html]  view plain copy
  1. FileInputStream inStream = context.openFileInput(ceshi.txt);//只需传文件名  
  2.     ByteArrayOutputStream outStream = new ByteArrayOutputStream();//输出到内存  
  3.       
  4.     int len=0;  
  5.     byte[] buffer = new byte[1024];  
  6.     while((len=inStream.read(buffer))!=-1){  
  7.         outStream.write(buffer, 0, len);//  
  8.     }  
  9.       
  10.     byte[] content_byte = outStream.toByteArray();  
  11.     String content = new String(content_byte);  
  12.     system.out.println(content)  

总结:重点注意的地方就是openFileOutput()的第一个参数和openFileInput()的参数,不需要写绝对路径,只需写文件名就可以了!

 

附言:当然读取数据时也可以用绝对路径,没有本文所述的方便,比如读取文件时可以用:

[java]  view plain copy
  1. Context context=MainActivity.this;//首先,在Activity里获取context    
  2. File file=context.getFilesDir();    
  3. String path=file.getAbsolutePath();   
  4. System.out.println(path);  
  5.           
  6. File file = new File(path+ceshi.txt);  
  7. FileInputStream inStream = new FileInputStream(file);//需传路径: /data/data/cn.itheima.rw_file/files/ceshi.txt  

上边几行的代码的作用仅仅相当于下边这一句代码的作用:

[java]  view plain copy
  1. context.openFileInput("ceshi.txt";  


何苦呢!你说呢!


——————————————————————————————————————————————————————————————————————————

实例:

写入 操作:

/* 保存用户登录信息列表 */
	public static void saveUserList(Context context, ArrayList<User> users)
			throws Exception {
		/* 保存 */
		Log.i(TAG, "正在保存");
		Writer writer = null;
		OutputStream out = null;
		JSONArray array = new JSONArray();
		for (User user : users) {
			array.put(user.toJSON());
		}
		try {
			out = context.openFileOutput(FILENAME, Context.MODE_PRIVATE); // 覆盖
			writer = new OutputStreamWriter(out);
			Log.i(TAG, "json的值:" + array.toString());
			writer.write(array.toString());
		} finally {
			if (writer != null)
				writer.close();
		}

	}


读取操作:

/* 获取用户登录信息列表 */
	public static ArrayList<User> getUserList(Context context) {
		/* 加载 */
		FileInputStream in = null;
		ArrayList<User> users = new ArrayList<User>();
		try {

			in = context.openFileInput(FILENAME);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder jsonString = new StringBuilder();
			JSONArray jsonArray = new JSONArray();
			String line;
			while ((line = reader.readLine()) != null) {
				jsonString.append(line);
			}
			Log.i(TAG, jsonString.toString());
			jsonArray = (JSONArray) new JSONTokener(jsonString.toString())
			.nextValue(); // 把字符串转换成JSONArray对象
			for (int i = 0; i < jsonArray.length(); i++) {
				User user = new User(jsonArray.getJSONObject(i));
				users.add(user);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return users;
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值