Android开发系列之数据存储(二)

上一篇记载了Android开发数据库与Sharepreferences的基本使用,该篇主要讲述下文件的存储方式。

  .文件

   文件存储方式在Android开发中几乎是必不可少的,常用的文件磁盘缓存,字符串文件缓存以及xml文件缓存等。

.文件读写 文件的读写主要有几种:多媒体文件以流的形式,文本文件以字符串的形式等。

.将流写入文件

/**
     * 将InputStream保存到文件
     *
     * @param context
     * @param in
     * @param fileLength
     * @param savDir
     * @param savName
     */
    public static void writeStream2File(Context context, InputStream in,
            long fileLength, String savDir, String savName) {

        if (in == null) {
            return;
        }
        if (StringUtils.isEmpty(savDir) || StringUtils.isEmpty(savName)) {
            return;
        }
        if (!canWrite(context, fileLength)) {
            return;
        }
        File dirFile = new File(savDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File savFile = new File(savDir, savName);
        try {
            if (savFile.exists()) {
                savFile.deleteOnExit();
            }
            savFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(savFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            fos = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

.将文件转化为流

public InputStream getInputStream(String path) {

   if(StringUtils.isEmpty(path)){

          return null;
    }

    File file = new File(path);
    if(!file.exists) {
        return null;
     }

     return new FileInputStream(file);
}

.将字符串写入文件

/**
     * 将String保存到文件
     *
     * @param context
     * @param content
     * @param dirPath
     * @param fileName
     * @param append
     *            写入形式:true-追加写入 、false-重新写入
     * @return
     */
    public static boolean writeString2File(Context context, String content,
            String dirPath, String fileName, boolean append) {

        if (StringUtils.isEmpty(content)) {
            return false;
        }
        if (StringUtils.isEmpty(dirPath) || StringUtils.isEmpty(fileName)) {
            return false;
        }
        File file = new File(dirPath, fileName);
        if (!file.exists()) {
            try {
                createNewDir(context, dirPath);
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file, append);
            fileWriter.write(content);
            fileWriter.close();
            fileWriter = null;
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                    fileWriter = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

.从文件读取字符串

/**
     * 读取文件
     *
     * @param context
     * @param filePath
     * @param charsetName
     * @return
     */
    public static StringBuilder readFile(Context context, File file,
            String charsetName) {
        if (file != null && file.exists() && SDCardUtils.sdcardExists()) {
            if (StringUtils.isEmpty(charsetName)) {
                charsetName = "UTF-8";
            }
            StringBuilder fileContent = new StringBuilder();
            BufferedReader reader = null;
            InputStreamReader is = null;
            try {
                is = new InputStreamReader(new FileInputStream(file),
                        charsetName);
                reader = new BufferedReader(is);
                String line = null;
                while ((line = reader.readLine()) != null) {
                    if (!fileContent.toString().equals("")) {
                        fileContent.append("\r\n");
                    }
                    fileContent.append(line);
                }
                is.close();
                reader.close();
                is = null;
                reader = null;
                return fileContent;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                        is = null;
                    }
                    if (reader != null) {
                        reader.close();
                        reader = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

.将文件转化为Base64字符串

/**
     * 文件转化Base64 String
     *
     * @param path
     *            文件完整路径
     * @return
     */
    public static String encodeFileByBase64(Context context, String dirPath,
            String fileName) {

        if (StringUtils.isEmpty(dirPath) || StringUtils.isEmpty(fileName)) {
            return null;
        }
        File file = new File(dirPath, fileName);
        if (!file.exists()) {
            return null;
        }
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) >= 0) {
                bos.write(buffer, 0, len);
            }
            String base64String = new String(Base64.encodeToString(
                    bos.toByteArray(), Base64.DEFAULT));
            fis.close();
            bos.close();
            fis = null;
            bos = null;
            return base64String;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
                if (bos != null) {
                    bos.close();
                    bos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

.将Base64字符串解析到文件

/**
     * Base64编码String解析到文件
     *
     * @param context
     * @param content
     * @param dirPath
     * @param fileName
     * @return
     */
    public static boolean decode2FileByBase64(Context context, String content,
            String dirPath, String fileName) {

        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(dirPath)
                || StringUtils.isEmpty(fileName)) {
            return false;
        }
        File file = new File(dirPath, fileName);
        try {
            if (file.exists()) {
                file.deleteOnExit();
                file.createNewFile();
            } else {
                createNewDir(context, dirPath);
                file.createNewFile();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        byte[] buffer = Base64.decode(content, Base64.DEFAULT);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(buffer);
            fos.close();
            fos = null;
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

.XML解析

      xml文件存储是常用的数据存储方式,xml解析常用的有SAX解析、DOM解析、PULL解析等。在讲述xml解析之前先讲述一下xml的格式以及如何将实体类保存为xml文件。

  . xml的存储格式

<persons>
    <person id="23">
        <name>eboy</name>
        <age>22</age>
    </person>
    <person id="24">
        <name>Frr</name>
        <age>20</age>
    </person>
</persons>

.将实体类集合保存到xml文件

/**
     * 将数据保存到xml文件
     *
     * @param persons
     * @param savePath
     * @throws Exception
     */
    public static boolean writeToXML(List<Person> persons, String savePath) {

        if (savePath == null || savePath.equals("")) {
            Log.e(TAG, "请输入正确的保存路径!");
            return false;
        }

        FileOutputStream out = null;

        try {
            //创建保存文件.如果存在,则删除并新建文件
            File file = new File(savePath);
            file.deleteOnExit();
            file.createNewFile();
            out = new FileOutputStream(file);

        } catch (Exception e) {
            Log.e(TAG, "无效的文件路径! " + e.getMessage());
            return false;
        }

        //创建XML序列化对象
        XmlSerializer serializer = Xml.newSerializer();
        //设置输出目标
        serializer.setOutput(out, "UTF-8");
        //开始解析
        serializer.startDocument("UTF-8", true);
        //设置开始根节点
        serializer.startTag(null, "persons");

        //将对象集合解析为节点
        for (Person person : persons) {

            // 开始解析父节点
            serializer.startTag(null, "person");
            serializer.attribute(null, "id", person.getId().toString()); //添加父节点属性

            // 子节点startTag/endTag要对称
            serializer.startTag(null, "name");
            serializer.text(person.getName().toString());//子节点值
            serializer.endTag(null, "name");

            serializer.startTag(null, "age");
            serializer.text(person.getAge().toString());
            serializer.endTag(null, "age");

            //结束解析父节点
            serializer.endTag(null, "person");
        }

        //设置结束根节点
        serializer.endTag(null, "persons");
        //解析结束
        serializer.endDocument();

        out.flush();
        out.close();
    }

时间: 2024-08-27 03:30:59

Android开发系列之数据存储(二)的相关文章

Android开发系列之数据存储(一)

  Android开发中,数据存储主要有五种:网络.数据库.SharePreferences.文件以及Content Provider.   . 数据库    Android中的数据库最常用的是Sqlite. 使用Sqlite进行数据存储,可分为以下几步:    . 继承SqliteOpenHelper    . 整理4个构造方法    . 重写onCreate与onUpgrade      public class DownDBHelper extends SQLiteOpenHelper {

android开发系列之数据存储

在我们的android实际开发过程,必不可少的一种行为操作对象就是数据.有些数据,对于用户而言是一次性的,这就要求我们每次进到App的时候,都需要去刷新数据.有些数据,对于用户而言又是具有一定时效性的,比如用户账号数据.这种情况下,就要求我们采用一定的数据保存措施,在这篇博客里面,我将为大家分享一些android里面常用的数据保存方法. 首先在android里面我们用的比较多的小数量存储方式可能就是SharedPreferences,那么什么是SharedPreferences呢?为了保存软件的

Android开发笔记之: 数据存储方式详解

无论是神马平台,神马开发环境,神马软件程序,数据都是核心.对于开发平台来讲,如果对数据的存储有良好的支持,那么对应用程序的开发将会有很大的促进作用.总体的来讲,数据存储方式有三种:一个是文件,一个是数据库,另一个则是网络.其中文件和数据库可能用的稍多一些,文件用起来较为方便,程序可以自己定义格式:数据库用起稍烦锁一些,但它有它的优点,比如在海量数据时性能优越,有查询功能,可以加密,可以加锁,可以跨应用,跨平台等等:网络,则用于比较重要的事情,比如科研,勘探,航空等实时采集到的数据需要马上通过网络

Android开发手记(20) 数据存储五 网络存储

Android为数据存储提供了五种方式: 1.SharedPreferences 2.文件存储 3.SQLite数据库 4.ContentProvider 5.网络存储 安卓的网络存储比较简单,因为Android提供的 Uri 和 Intent 可以帮助我们完成大多数任务. 一.发送邮件 首先,我们来看一下如何写一个发邮件的程序.前提是需要在系统邮件程序中配置好邮件发送的账户.由于发送邮件需要访问网络,所以我们需要添加如下权限: <uses-permission android:name="

Android开发手记(16) 数据存储一 SharedPreferences

SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据.这类似于C++中Map的数据存储方式(实际上在最后生成的.xml文件内,就是以Map格式存储的). 获取SharedPreferences的两种方式: 1.调用Context对象的getSharedPreferences()方法 2.调用Activity对象的getPrefer

Android开发-API指南-数据存储

Storage Options 英文原文:http://developer.android.com/guide/topics/data/data-storage.html 采集日期:2015-02-06 存储方式概述 用于简单数据的 Shared Preference 用于私有数据的内部存储 用于大型公开数据的外部存储 用于结构化数据的 SQLite 数据库 在本文中 使用 Shared Preference 使用内部存储 使用外部存储 使用数据库 使用网络连接 参阅 Content Provi

C#程序员学习Android开发系列之学习路线图

通过前面的3篇博客已经简单的介绍了Android开发的过程并写了一个简单的demo,了解了Android开发的环境以及一些背景知识. 接下来这篇博客不打算继续学习Android开发的细节,先停一下,明确一下接下来的学习目标以及学习路线. 一.对Android开发的基本认识 1.Android原生开发是基于Java语言的,由于我比较擅长C#,所以对Java语言本身不太熟练,需要加强Java语言基础的练习,这一块我会穿插到具体的知识点练习当中,并且在必要的地方给出与C#语言的对比(其实基本上在语法层

快速Android开发系列网络篇之Android-Async-Http

快速Android开发系列网络篇之Android-Async-Http 转:http://www.cnblogs.com/angeldevil/p/3729808.html 先来看一下最基本的用法 AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onSucce

C#程序员学习Android开发系列之ListView

上篇博客解决了Android客户端通过WebService与服务器端程序进行交互的问题,这篇博客重点关注两个问题,一个是Android应用程序如何与本机文件型数据库SQLite进行交互,另一问题则是如何在ListView中按照我们想要的界面效果进行展示.限于篇幅这篇重点讲ListView,下篇博客重点阐述SQLite. ListView是一个常用的数据显示控件,假设我们要做一个简单的界面,如图所示. 这张图是我直接从Android平板电脑(Android 4.2.2)上面截图下来的,就是一个普通