android 的文件操作说白了就是Java的文件操作的处理。所以如果对Java的io文件操作比较熟悉的话,android的文件操作就是小菜一碟了。好了,话不多说,开始今天的正题吧。


先从一个小项目入门吧


首先是一个布局文件,这一点比较的简单,那就直接上代码吧。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文件名称" />
    <EditText
        android:id="@+id/et_filename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="file name"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文件内容" />
    <EditText
        android:id="@+id/et_filecontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:lines="7"
        android:hint="file content"
        />
    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="toSave"
        android:text="Save"
        />
    <Button
        android:id="@+id/btn_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="getFile"
        android:text="Get"
        />

</LinearLayout>

然后是我们的主界面的Java文件了。继续上代码

package com.mark.storage;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.mark.service.FileService;

public class MainActivity extends Activity {

    private EditText mEt_filename,mEt_filecontent;
    private Button mBtn_save;

    private void init(){
        mEt_filecontent = (EditText) findViewById(R.id.et_filecontent);
        mEt_filename = (EditText) findViewById(R.id.et_filename);
        mBtn_save = (Button) findViewById(R.id.btn_save);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    /**
     * 保存数据到一个文件中
     * @param view
     */
    public void toSave(View view) {
        String fileName = mEt_filename.getText().toString();
        String fileContent = mEt_filecontent.getText().toString();
        FileService service = new FileService(getApplicationContext());
        boolean isSucceed = service.save(fileName, fileContent);
        if(isSucceed){
            Toast.makeText(getApplicationContext(), "恭喜您保存文件成功!", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getApplicationContext(), "对不起,您保存文件失败!", Toast.LENGTH_SHORT).show();
        }
    }

    public void getFile(View view){
        String fileName = mEt_filename.getText().toString();

        FileService service = new FileService(getApplicationContext());
        String fileContent = service.getFile(fileName);
        if(fileContent!=null || !fileContent.equals("")) {
            mEt_filecontent.setText(fileContent);
        }else{
            Toast.makeText(getApplicationContext(), "对不起,读取文件失败!", Toast.LENGTH_SHORT).show();
        }

    }

}

是不是感觉里面的代码有点奇怪呢?FileService是什么鬼?

其实FileService就是我们的业务类,主要的功能就是帮助我们实现了对文件的保存和读取等操作。下面也贴出代码

package com.mark.service;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.content.Context;

public class FileService {

    //android自带的可以快速获得文件输出流的一个类,注意参数不能是路径,只能是文件名称
    private Context mContext;

    public FileService(Context context) {
        this.mContext = context;
    }

    /**
     * 保存文件的一个方法
     * @param fileName
     * @param fileContent
     * @return
     */
    public boolean save(String fileName, String fileContent) {
        try {
            //采用Context.MODE_PRIVATE模式的话,只允许本应用访问此文件,并且熟覆盖式的添加数据
            FileOutputStream fos = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
            fos.write(fileContent.getBytes());
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 获得之前保存过的文件的详细的信息
     * @param fileName
     * @return
     */
    public String getFile(String fileName) {
        String fileContent = "";
        try{

            FileInputStream fis = mContext.openFileInput(fileName);
            byte[] buf = new byte[1024];
            int len;
            ByteArrayOutputStream bais = new ByteArrayOutputStream();
            while((len = fis.read(buf))!= -1){
                bais.write(buf, 0, len);
            }
            byte[] data = bais.toByteArray();
            fileContent = new String(data);
            fis.close();
            return fileContent;
        }catch(Exception e){
            e.printStackTrace();
            return "对不起,读取文件失败!";
        }

    }

}

业务类的分析


现在开始进入正题咯。这个小项目的核心就在于这个业务类,原因如下:

  • Context:Android自带的上下文类,方便获得file流对象
  • 读文件方法中使用到了ByteArrayOutputStream类,这一点是很重要的,如果只是单纯的使用字符串来读取存储的文件的话,就会因为序列化的问题而出现不了目标数据。
  • 使用了返回值来对操作的结果进行了“反馈”,方便为用户提供友好的界面和使用体验。

核心


分层的思想,不同的功能的类放置到不同的包内,这样既方便程序的调试,也方便今后的代码的维护。

Android 文件操作心得体会的更多相关文章

  1. android 文件操作类简易总结

    android 文件操作类(参考链接) http://www.cnblogs.com/menlsh/archive/2013/04/02/2997084.html package com.androi ...

  2. Java和Android文件操作

    File这是文件基类,抽象地代表一个文件实体,它有四个不同的构造方法: File(File dir, String name)  File(String path)   File(String dir ...

  3. Android 文件操作之openFileOutput

    openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 会自动创建它.创建的文件保存在/data/data/<package ...

  4. Android文件操作

    将数据写入Internal Storage: String fileName = "myfile.txt"; String str="保存数据到内部存储"; t ...

  5. 大过年的,不下班的,上个Android文件操作类(内部存储和sd卡均可)

    package com.kkdiangame.UI.res; import java.io.ByteArrayOutputStream; import java.io.File; import jav ...

  6. 转:Android文件操作总结

    http://www.cnblogs.com/devinzhang/archive/2012/01/19/2327597.html http://blog.sina.com.cn/s/blog_5a4 ...

  7. Android文件操作报open failed: EBUSY (Device or resource busy)

    Android删除文件后重新创建时偶尔出现 open failed: EBUSY (Device or resource busy)错误,该错误是Android系统的一个bug,大概的意思类似于win ...

  8. 转 Android - 文件操作

    一.资源文件的读取: 1) 从resource的raw中读取文件数据: String res = ""; try{ //得到资源中的Raw数据流 InputStream in = ...

  9. Android数据存储-文件操作

    一.预备知识 1.Android中的MVC设计模式 MVC (Model-View-Controller):M是指逻辑模型,V是指视图模型,C则是控制器.一个逻辑模型可以对于多种视图模型,比如一批统计 ...

随机推荐

  1. Linux(CentOs6.3)网络配置

    新装好的虚拟机往往还无法连接网络,本文描述了如何在CentOs6.3系统上配置网络信息 1.windows系统下快捷键windows+r,输入cmd并确定,打开黑窗口 2.黑窗口中输入ipconfig ...

  2. Delphi7 ADO面板上的控件简介

    ? ADO Connection的主要方法:1) Begin Trans    开始启动一个新的事务,必须保证数据连接处于激活状态.2) Cancel    关闭于数据库的连接.3) Commit T ...

  3. Linux学习之CentOS(五)--CentOS下VMware-Tools安装

    已经进入到了Linux学习之CentOS的第六篇随笔了,所以这里就介绍一下VMware-Tools的安装. VMware-Tools的安装 VMware-Tools 主要的功能就是让用户在虚拟机和真实 ...

  4. VMWare - Ubuntu 64 (16.04)之扩容介绍

    背景 貌似是一个老生常谈的问题哈,由于自己之前也没有弄过,今天正好有时间稍微折腾了一下. 这里就选择最简单的方式来为大家呈现. VMWare 的设置 没有什么可以过多说的,完全是图形操作.这里直接上图 ...

  5. python之with的使用

      python之with使用                                         with工作原理            紧跟with后面的语句被求值后,返回对象的__e ...

  6. java底层学习

    额,马上就要面试了,Java的底层肯定是需要了解的.网上找了找java的底层文章,做个记号.java底层主要是类的加载.连接和初始化. 本文主要分为四个方面: (1)java底层概述 (2)new和n ...

  7. Linux阿里云挂载磁盘,并开机自动挂载

    Linux下磁盘挂载 公司新订购阿里云ECS,需要挂载当前的磁盘.暂时没有运维,自己动手挂载磁盘. 具体步骤如下: 1.查看是否已经分配 [root@iZ2ze1tefvghtbgkdur3xfZ / ...

  8. python类(class)中参数self的解释说明

    python类(class)中参数self的简单解释 1.self只有在类的方法中才会有,其他函数或方法是不必带self的. 2.在调用时不必传入相应的参数.3.在类的方法中(如__init__),第 ...

  9. MongoDB 连接

    启动 MongoDB服务 在前面的教程中,我们已经讨论了如何启动MongoDB服务,你只需要在MongoDB安装目录的bin目录下执行'mongod'即可. 执行启动操作后,mongodb在输出一些必 ...

  10. Rails关闭html_safe字符串过滤

    在某些情况下我希望html的文本中包含一些换行,因为html5产生换行的方法是插入 <br />所以我可以这么写: text = "hello world!<br /> ...