Android 数据存取

本文介绍了在Android应用中如何进行数据的读取和写入操作,包括使用FileInputStream和FileOutputStream进行基本的数据读写,以及利用Properties类进行更为便捷的配置文件管理。

在android文件系统中,application 文件存放在/data/data/package_name/files 目录。

 

数据读取

    1. public static String read(Context context, String file) {  
    1. String data = "";  
    2. try {  
    3. FileInputStream stream = context.openFileInput(file);  
    4. StringBuffer sb = new StringBuffer();  
    5. int c;  
    6. while ((c = stream.read()) != -1) {  
    7. sb.append((char) c);  
    8. }  
    9. stream.close();  
    10. data = sb.toString();  
    11.  
    12. catch (FileNotFoundException e) {  
    13. catch (IOException e) {  
    14. }  
    15. return data;  
  • 数据写入

     

    1. public static void write(Context context, String file, String msg) {  
    1. try {  
    2. FileOutputStream stream = context.openFileOutput(file,  
    3. Context.MODE_WORLD_WRITEABLE);  
    4. stream.write(msg.getBytes());  
    5. stream.flush();  
    6. stream.close();  
    7. catch (FileNotFoundException e) {  
    8. catch (IOException e) {  
    9. }  
  •  

    在这里打开文件的时候,声明了文件打开的方式。

    一般来说,直接使用文件可能不太好用,尤其是,我们想要存放一些琐碎的数据,那么要生成一些琐碎的文件,或者在同一文件中定义一下格式。其实也可以将其包装成Properties来使用:

    1. public static Properties load(Context context, String file) {  
    1. Properties properties = new Properties();  
    2. try {  
    3. FileInputStream stream = context.openFileInput(file);  
    4. properties.load(stream);  
    5. catch (FileNotFoundException e) {  
    6. catch (IOException e) {  
    7. }  
    8. return properties;  
    9. }  
    10.  
    11. public static void store(Context context, String file, Properties properties) {  
    12. try {  
    13. FileOutputStream stream = context.openFileOutput(file,  
    14. Context.MODE_WORLD_WRITEABLE);  
    15. properties.store(stream, "");  
    16. catch (FileNotFoundException e) {  
    17. catch (IOException e) {  
    18. }  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值