Android 文件操作心得体会

本文通过一个简单的Android项目实例,介绍了如何使用Java进行文件操作,并深入解析了一个用于保存和读取文件的业务类的设计与实现。文章还详细解释了Context的作用、ByteArrayOutputStream的重要性以及反馈机制在代码中的应用。

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文件架构详解 cache : 是缓存临时文件夹,据说是除了T-mobile的OTA更新外,别无用处。 红色标记的两个文件是debug模式下产生的 data : 存放用户安装的软件以及各种数据。 default.prop : 默认配置文件 dev : 设备节点文件的存放地 etc : 指向 /system/etc ,配置文件存放目录 init : 系统启动到文件系统的时候第一个运行的程序。 init.goldfish.rc : 初始化文件 init.rc : 初始化文件 proc : /proc文件系统下的多种文件提供的系统信息不是针对某个特定进程的,而是能够在整个系统范围的上下文中使用。 root : 为空 。 sbin: 只放了一个用於调试的adbd程序 sdcard: 是SD卡中的FAT32文件系统挂载的目录 sqlite_stmt_journals: 一个根目录下的tmpfs文件系统,用於存放临时文件数据。 sys : 用於挂载 sysfs文件系统。 在设备模型中,sysfs文件系统用来表示设备的结构.将设备的层次结构形象的反应到用户空间中.用户空间可以修改sysfs中的文件属性来修改设备的属性值 system :系统中的大部分东西都在这各目录下,很重要的一个目录文件 system目录是在Android文件系统占有及其重要的位置,基本上所有的工具和应用程序都在这个目录下,我看来是一个真正的rootfs。他在Android手机中存放在nandflash的 mtd3中,是一个yaffs2文件系统,在启动时被挂载在root的/system目录下,其中包含有: # ls -a -l /system drwxr-xr-x root 208 1970-01-01 08:00 xbin drwxr-xr-x root root 1970-01-01 08:00 modules drwxr-xr-x root root 2010-06-23 09:39 framework drwxr-xr-x root root 2010-06-23 09:39 fonts drwxr-xr-x root root 2010-06-23 09:39 etc -rw-r--r-- root root 2197 2010-06-23 09:39 build.prop drwxr-xr-x root root 2010-06-23 09:39 media drwxr-xr-x root shell 2010-06-23 09:39 bin drwxr-xr-x root root 2010-06-23 09:39 usr drwxr-xr-x root root 2010-06-23 09:39 app drwxr-xr-x root root 2010-06-23 09:39 lost+found drwxr-xr-x root root 2010-06-23 09:39 lib drwxr-xr-x root root 2010-06-23 09:39 sd -rw-r--r-- root root 1452010-06-23 09:39 init.rc # xbin :下放了很多系统管理工具,这些工具不是到toolbox的链接,每个都是可执行程序。如果你看到这些命令你会发现他们根本不常用,他们都是为系统管理员准备的,是一些系统管理和配置工具。这个文件夹的作用相当於标准Linux文件系统中的 /sbin。 modules:使用来存放内核模块(主要是fs和net)和模块配置文件的地方。 framework: 是JAVA平台的一些核心文件,属於JAVA平台系统框架文件。里面的文件都是.jar和.odex文件。 备注:什么是odex文件? odex是被优化过的JAVA程序文件,体积通常是.jar的4倍左右。执行效率比.jar高。 fonts :字体库文件的存放目录。 etc :这里存放了系统中几乎所有的配置文件,根目录下的/etc就链结於此。 build.prop :是一个属性文件,在Android系统中.prop文件很重要,记录了系统的设置和改变,类似於/etc中的文件。 media :里面主要是存放了系统的铃声的,分为 notifications(通知)、ui(界面)、alarms(警告)和ringtones(铃声),里面都是.ogg音频文件。 bin :是存放用户常用的工具程序的,其中大部分是到toolbox的链接(类似嵌入式Linux中的busybox)。toolbox应该是 google简化版的busybox。 usr :用户的配置文件,如键盘布局、共享、时区文件等等。您可以cat 来看看。 app :存放的是Android系统自带的JAVA应用程序。 lost+found :yaffs文件系统固有的,类似回收站的文件夹,只有是yaffs文件系统都会有。 lib :存放几乎所有的共享库(.so)文件。 sd :SD卡中的EXT2分区的挂载目录 init.rc :一个初始化脚本,用於将/system/modules和/system/xbin挂载为cramfs,避免系统被无意破坏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泰 戈 尔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值