zoukankan      html  css  js  c++  java
  • android 数据持久化——I/O操作

    上一节中简单的介绍了File的操作,这一节来说说使用android平台自带对象实现文件的基本操作

    主要的两个类:openFileOutput(写)和openFileInput(读)


    向文件中写如数据代码如下:

    //向文件写入内容
    		try {
    			OutputStream os = openFileOutput("file-io.txt", Context.MODE_PRIVATE);
    			String str = "向文件中写入数据";
    			os.write(str.getBytes("utf-8"));
    			os.close();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}


    读取文中的代码如下:

    //读取文件中的内容
    		try {
    			InputStream is = openFileInput("file-io.txt");
    			byte[] buffer = new byte[100];
    			int byteLength = is.read(buffer);
    			String str2 = new String(buffer, 0, byteLength, "utf-8");
    			text.setText(str2.toString());
    			is.close();
    		}  catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}


    从上面的代码中可以看出:openFileOutput / openFileInput 的用法与之前的SharedPreferences 的用法有很大的相似性,下面简单说一下两者的异同:


    SharedPreferences对象的创建:

    SharedPreferences sp = getSharedPreferences("file",Contex.MODE_PRIVATE);

    getSharedPreferences方法的第一个参数是指定要保存在手机内存中的文件名(不包括扩展名,扩展名为xml),第二个参数是表示SharedPreferences对象在创建XML文件时设置的文件属性;

    Context.MODE_PRIVATE = 0 (默认),代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
    Context.MODE_APPEND = 32768
    Context.MODE_WORLD_READABLE = 1
    Context.MODE_WORLD_WRITEABLE = 2


    openFileOutput 方法是如何返回一个OutputStream对象的:

    OutputStream os = openFileOutput("file.xml",Contex.MODE_PRIVATE);


    openFileOutput 的第一个参数指定的文件名带有扩展名,第二个参数与getSharedPreferences的是一样的;从这两个方法来看,第一个参数只制定了文件名,并未包含文件的路径,因此, 这两个方法只能将文件保存在手机的内存中固定的路径 对于大文件可能内存不够

    SharedPreferences 将XML 文件保存在:/data/data/<包名>/shared_prefs

    openFileOutput 将文件保存在:/data/data/<包名>/files

    Activity还提供了getCacheDir()和getFilesDir()方法:

    getCacheDir()方法用于获取:/data/data/<package name>/cache 目录 

    getFilesDir()方法用于获取:/data/data/<package name>/files 目录。

  • 相关阅读:
    POJ 1469 COURSES 二分图最大匹配
    POJ 1325 Machine Schedule 二分图最大匹配
    USACO Humble Numbers DP?
    SGU 194 Reactor Cooling 带容量上下限制的网络流
    POJ 3084 Panic Room 求最小割
    ZOJ 2587 Unique Attack 判断最小割是否唯一
    Poj 1815 Friendship 枚举+求最小割
    POJ 3308 Paratroopers 最小点权覆盖 求最小割
    1227. Rally Championship
    Etaoin Shrdlu
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3206551.html
Copyright © 2011-2022 走看看