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. Sql Server 镜像相关

    http://blog.csdn.net/dba_huangzj/article/details/35995083

  2. 微信小程序-参数传递与事件处理

    前言 开发过程中经常会遇到从一个页面携带数据到另一个页面的情况,所以需要知道以下信息,什么是事件?有哪些传递方式?如果传递数组呢?如果传递对象呢? 一.事件 什么是事件 事件是视图层到逻辑层的通讯方式 ...

  3. 【Tensorflow系列】使用Inception_resnet_v2训练自己的数据集并用Tensorboard监控

    [写在前面] 用Tensorflow(TF)已实现好的卷积神经网络(CNN)模型来训练自己的数据集,验证目前较成熟模型在不同数据集上的准确度,如Inception_V3, VGG16,Inceptio ...

  4. jQuery简单笔记

    jQuery 是一个 JavaScript 库,简化了 JavaScript 的编程. 语法:$(selector).action() selector 是字符串,表示HTML元素. 对象 符号 例子 ...

  5. json转化为对象数组

    1.ascx传值给aspx aspx页面 <%@ Page Title="" Language="C#" MasterPageFile="~/_ ...

  6. Linux安装JProfiler监控tomcat

    下载JProfiler包wget http://download-keycdn.ej-technologies.com/jprofiler/jprofiler_linux_9_2.rpm 安装JPro ...

  7. 小白的Python之路_day2

    Python 的逻辑运算符具有短路原则,例如: or 运算符前面只要是 True,后面都不需要看了,结果就是 True.  Python 中表示为真必须用 True,如果用 true 则会当成是变量, ...

  8. 58. Length of Last Word(easy, 字符串问题)

    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...

  9. pycharm 安装与基本设置

    一.下载及安装 打开官网下载:https://www.jetbrains.com/pycharm/download/#section=windows 下载完毕之后可直接双击可执行文件,然后点击&quo ...

  10. PHP MySQL 创建数据表

    PHP 创建 MySQL 表 一个数据表有一个唯一名称,并有行和列组成. 使用 MySQLi 和 PDO 创建 MySQL 表 CREATE TABLE 语句用于创建 MySQL 表. 我们将创建一个 ...