第一章 数据与文件储存

=============================访问数据文件==============================

文件的写入与读取:

Activity中获取文件流的方法:

      FileOutputStream openFileOutputStream(String 文件路径+文件名, int 文件访问模式)

           文件访问模式的可选值:

                 Context.MODE_APPEND--------------打开文件并在文件添加

                 Context.MODE_PRIVATE-------------共程序本身读写私有方式打开文件

                 Context.MODE_WORLD_READABLE------可供其他应用程序读取的方式打开文件(不推荐)

                 Context.MODE_WORLD_WRITEABLE------可供其他应用程序写入的方式打开文件(不推荐)

      使用代码: 

1 BufferedOutputStream bos = new BufferedOutputStream(
2     openFileOutputStream("文件名.txt", MODE_PRIVATE));
3 bos.write("要保存的文件内容String".getBytes("UTF-8"));

  或者:

1 BufferedWriter bw = new BufferedWriter(
2     new OutputStreamWriter(openFileOutput(filename, MODE_PRIVATE)));
3 bw.write("要保存的文件内容String");

     

  

   FileInputStream opneFileInputSrteam(String 文件路径+文件名)

      使用代码:

1 BufferedInputStream bis = new BufferedInputStream(openFileInput(filename));
2 byte[] bytes = new byte[100];
3 int iscontinue;
4 while((iscontinue = bis.read(bytes)) != -1)
5 {
6     System.out.print(new String(bytes, 0, bytes.length));
7 }

  或者:

1 BufferedReader br = new BufferedReader(
2         new InputStreamReader(openFileInput(filename)));
3 String line = "";    
4 while(line != null)
5 {
6     System.out.println(line);
7     line = br.readLine();
8 }

           **注: 如果不指定文件路径, 则默认访问/data/data/<package name>/files目录下的文件

 

Activity还提供了其他文件操作方法:

      String[] fileList()---------------------获取私有目录下的所有文件名的数组列表

      File getFilesDir()----------------------获取该Activity所属文件路径的File对象

      boolean deleteFile(String filename)-----删除指定文件

 

           小技巧:

//通过getFilesDir().getPath().toString()获取路径,再获取文件File对象

File file = new File(getFilesDir().getPath().toString() + "/" + filename);

//获取File对象的长度

int fileLength = (int)file.length();

 

 

案例代码:

 1 public class MainActivity extends Activity
 2 {
 3 
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState)
 6     {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         
10         final String filename = "我的文件.txt";
11         final String context = "这是我写的要保存的文件内容的第一行" + 
12                 "\n这是我写的要保存的文件内容的第二行" +
13                 "\n这是我写的要保存的文件内容的第3行" +
14                 "\n这是我写的要保存的文件内容的第4行";
15         save(filename, context);
16         
17         load(filename);
18     }
19 
20     /**
21      * 用输出流保存文件
22      * @param filename
23      * @param context
24      */
25     private void save(String filename, String context)
26     {
27         FileOutputStream fos = null;
28         OutputStreamWriter osw = null;
29         BufferedWriter bw = null;
30         
31         try
32         {
33             fos = openFileOutput(filename, MODE_PRIVATE);
34             osw = new OutputStreamWriter(fos);
35             bw = new BufferedWriter(osw);
36             
37             bw.write(context);
38         } 
39         catch (IOException e)
40         {
41             e.printStackTrace();
42         }
43         finally
44         {
45             if(bw != null)
46             {
47                 try
48                 {
49                     bw.close();
50                 }
51                 catch (IOException e)
52                 {
53                     e.printStackTrace();
54                 }
55             }
56         }
57     }
58     
59     /**
60      * 注意String line 的 System.out.println(null)会报NullPointerException
61      * 读取filename文件里的数据
62      * @param filename
63      */
64     private void load(String filename)
65     {
66         BufferedReader br = null;
67         
68         try
69         {
70             br = new BufferedReader(
71                     new InputStreamReader(openFileInput(filename)));
72             String line = "";    
73             while(line != null)
74             {
75                 System.out.println(line);
76                 line = br.readLine();
77             }
78         } 
79         catch (IOException e)
80         {
81             e.printStackTrace();
82         }
83         finally
84         {
85             if(br != null)
86             {
87                 try
88                 {
89                     br.close();
90                 } 
91                 catch (IOException e)
92                 {
93                     e.printStackTrace();
94                 }
95             }
96         }
97     }
98 
99 }

 

 

=============================Shared Preference储存机制=========================

保存:

      1.获取SharedPreferences对象

SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);

      2.获取SharedPreferences.Editor编辑器对象

Editor editor = sp.edit();

      3.Editor对象中写入数据

editor.putString("key", data);

      4.调用commit()方法提交数据,完成数据储存操作

editor.commit();//commit 使...承担v

 

读取:

      1.获取SharedPreferences对象

SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);

      2.获取数据

String data = sp.getString("key", "");

 

    实例代码:

 1 public class MainActivity extends Activity
 2 {
 3     private Button btn_savedata, btn_loaddata;
 4     private EditText et; 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState)
 7     {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_main);
10         btn_savedata = (Button) findViewById(R.id.btn_savedata);
11         btn_loaddata = (Button) findViewById(R.id.btn_loaddata);
12         et = (EditText) findViewById(R.id.et);
13         
14         btn_savedata.setOnClickListener(new OnClickListener()
15         {
16             
17             @Override
18             public void onClick(View v)
19             {    
20                 String data = et.getText().toString();
21                 //获取SharedPreferences对象
22                 SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);
23                 Editor editor = sp.edit();//获取SharedPreferences.Editor编辑器对象
24                 editor.putString("key", data);//Editor对象中写入数据
25                 editor.commit();//调用commit()方法提交数据,完成数据储存操作   commit 使...承担v
26                 
27                 
28                 et.setText("");
29             }
30         });
31         
32         btn_loaddata.setOnClickListener(new OnClickListener()
33         {
34             
35             @Override
36             public void onClick(View v)
37             {
38                 //获取SharedPreferences对象
39                 SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);
40                 String data = sp.getString("key", "");//获取数据
41                 
42                 if(data.length() == 0)
43                 {
44                     data = "没有存储数据";
45                 }
46                 et.setText(data);
47             }
48         });
49     }
50 }

 

posted on 2015-12-05 15:19  starFarming  阅读(197)  评论(0编辑  收藏  举报