W e S D
0 1

[安卓基础] 012.存储数据(下)——文件存储

存储数据(下)——文件存储

这篇文章学到的内容:
1、回顾之前学习的三种数据存储方式(SharedPreferences、xml和Sqlite)
2、文件存储(存储数据到data/data/packagename/files和存储数据到sdcard)

1、回顾之前学习的三种数据存储方式(SharedPreferences、xml和Sqlite)

SharedPreferences

轻量级的存储类,主要保存一些常用的配置,适合用简单的数据类型,int、String、boolean等。它的本质也是基于xml来存储key-value键值对数据。

Xml存储

轻量级的存储类,如果数据量不大,但是数据又比较复杂,可以选择使用这种方式存储数据。可以自定义xml标签格式。处理xml时,能通过自带底层的本地xml Parser来解析xml。这里建议采用xmlpull方式来操作xml

Sqlite存储

功能强大,可以实现数据库的许多操作。它就是一个轻量级的数据库,被设计用于嵌入式的设备,所以android采用sqlite来作为支持的关系型数据库管理系统。到2015年,sqlite已经到sqlite3了,具体的操作,和我们常见的数据库一样。如果数据量大,而且有许多关系表,建议采用数据库来做数据存储。

2、进入主题,介绍文件存储方式

android除了上面的三种方式,还有三种数据存储:文件存储、contentProvider存储,网络存储。这里介绍文件存储。后两个以后会讲。

3、文件存储

文件存储的方式,说白了就是通过流的方式来创建文件来存储数据。只不过,我们是在手机的存储卡中来创建这些文件的。

存储数据到data/data/packagename/files

关键代码就是Context.openFileOutput(fileName, mode);执行这句话,会在data/data/packagename/files目录下创建fileName文件,我们可以用流的方式把数据写入到fileName中。mode是文件模式。你可也在后面的文件模式查看android支持的缓存文件模式。

存内容

这里只贴关键代码。

 1     /**
 2      * 存储内容到data/data/packagename/file
 3      * 
 4      * @param act
 5      * @param content
 6      *            文件内容
 7      * @param fileName
 8      *            文件名
 9      * @param mode
10      *            模式
11      */
12     public static void saveContentToDataFile(Activity act, String content,
13             String fileName, int mode) {
14 
15         try {
16             FileOutputStream fos = act.openFileOutput(fileName, mode);
17             fos.write(content.getBytes("UTF-8"));
18             fos.close();
19         } catch (Exception e) {
20             e.printStackTrace();
21         }
22     }

 

读内容

这里只贴关键代码。

 1     /**
 2      * 读取data/data/packagename/file/fileName文件中的字符内容
 3      * @param act
 4      * @param fileName
 5      * @return
 6      */
 7     public static String readContentFromDataFile(Activity act, String fileName) {
 8 
 9         String result = "";
10         try {
11             FileInputStream in = null;
12             ByteArrayOutputStream bout = null;
13             byte[] buf = new byte[1024];
14             bout = new ByteArrayOutputStream();
15             int length = 0;
16             in = act.openFileInput(fileName); // 获得输入流
17             while ((length = in.read(buf)) != -1) {
18                 bout.write(buf, 0, length);
19             }
20             byte[] content = bout.toByteArray();
21             result = new String(content, "UTF-8"); 
22             in.close();
23             bout.close();
24         } catch (Exception e) {
25             e.printStackTrace();
26         }
27         return result;
28     }

 

检查文件是否存在

这里只贴关键代码。

 1     /**
 2      * 检查file是否存在
 3      * @param act
 4      * @param fileName
 5      * @return
 6      */
 7     public static boolean checkFileIsExistInData(Activity act, String fileName){
 8         
 9         boolean result = false;
10         File file = act.getFileStreamPath(fileName);
11         if (file != null && file.exists()) {
12             result = true;
13         }
14         return result;
15     }

 

文件模式

1.Context.MODE_PRIVATE:私有覆盖模式

只能被当前应用访问,并且如果写入,则覆盖。

2.Context.MODE_APPEND:私有追加模式

只能被当前应用访问,并且如果写入,则追加。

3.Context,MODE_WORLD_READABLE:公有只读模式

可以被其他应用读取。

4.Context.MODE_WORLD_WRITEABLE:公有可写模式

可以被其他应用写入,但不能读取。 注意,如果希望其他使得文件模式叠加,则可以使用加号连接:
比如:Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE表示其他应用可读写。

存储文件到SDCard

关键代码,就是要获得sdcard的根路径。Environment.getExternalStorageDirectory()就是得到当前外部存储设备的根目录。

检测sdcard设备是否存在

这里只贴关键代码。

 1     public static boolean checkSDCARD() {
 2 
 3         String status = Environment.getExternalStorageState();
 4 
 5         if (status.equals(Environment.MEDIA_MOUNTED)) {
 6             return true;
 7         }
 8 
 9         return false;
10     }

 

在sdcard中创建目录

这里只贴关键代码。

 1     public static boolean createDir2SDCard(String path) {
 2 
 3         File dir = new File(path);
 4 
 5         if (!dir.exists()) {
 6             return dir.mkdirs();
 7         }
 8 
 9         return true;
10     }

 

在sdcard中创建文件

这里只贴关键代码。

 1     public static File createFile2SDCard(String path, String fileName) {
 2 
 3         // ///////////////////////////////////////
 4         // 创建SD卡目录
 5         // ///////////////////////////////////////
 6         File dir = new File(path);
 7 
 8         if (!dir.exists()) {
 9             dir.mkdirs();
10         }
11 
12         // //////////////////////////////////////////
13         // 创建SD卡文件
14         // ///////////////////////////////////////////
15         File file = new File(path + fileName);
16 
17         if (file.exists()) {
18 
19             file.delete();
20         }
21 
22         try {
23             file.createNewFile();
24         } catch (IOException e) {
25             // TODO Auto-generated catch block
26             e.printStackTrace();
27         }
28 
29         return file;
30     }

 

在sdcard中删除目录和目录下的所有文件

这里只贴关键代码。

    public static boolean deleteDir4SDCard(String path) {

        File dir = new File(path);

        if (dir.exists()) {
            File[] files = dir.listFiles();

            for (File file : files) {

                file.delete();
            }

            dir.delete();
        }

        return true;
    }

 

在sdcard中检查文件是否存在

这里只贴关键代码。

 1     public static boolean checkFileExist(String path) {
 2 
 3         File file = new File(path);
 4 
 5         if (file.exists()) {
 6 
 7             return true;
 8         }
 9 
10         return false;
11     }

 

在sdcard中创建文件并写入内容

这里只贴关键代码。

 1     /**
 2      * 保存内容到sdcard
 3      * @param act
 4      * @param content
 5      * @param fileName
 6      * @param mode
 7      */
 8     public static void saveContentToSDCardFile(Activity act, String content,
 9             String fileName) {
10 
11         if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 如果sdcard插入
12             try {
13                 String sdcardRootPath = Environment.getExternalStorageDirectory() + "/";
14                 FileOutputStream fos = new FileOutputStream(sdcardRootPath + fileName); 
15                 fos.write(content.getBytes("UTF-8"));
16                 fos.close();
17             } catch (Exception e) {
18                 e.printStackTrace();
19             }
20         }
21     }

 

在sdcard中读取内容

这里只贴关键代码。

 1     /**
 2      * 从sdcard中某个文件读取内容
 3      * @param act
 4      * @param fileName
 5      * @return
 6      */
 7     public static String readContentFromSDCardFile(Activity act, String fileName) {
 8 
 9         String result = "";
10         if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 如果sdcard插入
11             String sdcardRootPath = Environment.getExternalStorageDirectory() + "/";
12             try {
13                 FileInputStream in = null;
14                 ByteArrayOutputStream bout = null;
15                 byte[] buf = new byte[1024];
16                 bout = new ByteArrayOutputStream();
17                 int length = 0;
18                 in = new FileInputStream(sdcardRootPath + fileName); 
19                 while ((length = in.read(buf)) != -1) {
20                     bout.write(buf, 0, length);
21                 }
22                 byte[] content = bout.toByteArray();
23                 result = new String(content, "UTF-8"); 
24                 in.close();
25                 bout.close();
26             } catch (Exception e) {
27                 e.printStackTrace();
28             }
29         }
30         return result;
31     }

 

 

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 
转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4809580.html

 

posted @ 2015-09-15 10:48  SD.Team  阅读(392)  评论(0编辑  收藏  举报