Android 数据存取

来源:互联网 发布:六扇门调查知乎 编辑:程序博客网 时间:2024/06/10 00:32

在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. }  
  • 原创粉丝点击