Android学习笔记三十二之数据存储—文件存储读取

我们知道,在AndroidOS中,提供了五中数据存储方式,分别是:ContentProvider存储、文件存储、SharedPreference存储、SQLite数据库存储、网络存储。其中ContentProvider存储在我们介绍ContentProvider的时候已经介绍过了,现在我们学习其它的数据存储方式。这一篇,我们介绍文件存储。

1、文件的操作模式

  我们在学Java的时候都知道,Java中的IO操作来进行文件的保存和读取,Android是基于Linux的,与Java不同的是android在Context类中封装好了输入流和输出流的获取方法,分别是: FileInputStream openFileInput(String name); FileOutputStream(String name , int mode),这两个方法第一个参数 用于指定文件名,第二个参数指定打开文件的模式。Android提供的文件模式有:

  • MODE_PRIVATE:Android提供的默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容。

  • MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。

  • MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;

  • MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

此外,Android还提供了其它几个重要的文件操作的方法:

  • getDir(String name , int mode):在应用程序的数据文件夹下获取或者创建name对应的子目录

  • File getFilesDir():获取app的data目录下的绝对路径

  • String[] fileList():返回app的data目录下数的全部文件

  • deleteFile(String fileName):删除app的data目录下的指定文件

2、读写文件

  Android的读写文件和Java一样,也是一样通过IO操作实现,下面我们通过一个简单的例子走一下这个流程:

布局文件代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
    android:id="@+id/ed_file_save"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btn_file_save"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="保存内容" />

<Button
    android:id="@+id/btn_file_read"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="读取内容" />

<TextView
    android:id="@+id/tv_read_file"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:textColor="#000"
    android:textSize="14sp" />

</LinearLayout>

Activity代码:

package com.example.datasave;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Devin on 2016/7/19.
 */
public class FileDataActivity extends AppCompatActivity {
private EditText ed_file_save;
private Button btn_file_save;
private Button btn_file_read;
private TextView tv_read_file;
private String fileName = " hello.txt";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file);
    ed_file_save = (EditText) findViewById(R.id.ed_file_save);
    btn_file_save = (Button) findViewById(R.id.btn_file_save);
    btn_file_read = (Button) findViewById(R.id.btn_file_read);
    tv_read_file = (TextView) findViewById(R.id.tv_read_file);

    btn_file_save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String fileContent = ed_file_save.getText().toString();
            try {
                save(fileContent);
                ToastUtils.showToast(FileDataActivity.this, "文件写入成功");
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showToast(FileDataActivity.this, "文件写入失败");
            }
        }
    });
    btn_file_read.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                String content = read();
                tv_read_file.setText("文件的内容是:" + content);
            } catch (IOException e) {
                e.printStackTrace();
                ToastUtils.showToast(FileDataActivity.this, "读取文件失败!");
            }
        }
    });
}

public void save(String fileContent) throws Exception {
    FileOutputStream output = this.openFileOutput(fileName, Context.MODE_PRIVATE);
    output.write(fileContent.getBytes());
    output.close();
}

public String read() throws IOException {
    //打开文件输入流
    FileInputStream input = this.openFileInput(fileName);
    byte[] temp = new byte[1024];
    StringBuffer stringBuffer = new StringBuffer("");
    int len = 0;
    while ((len = input.read(temp)) > 0) {
        stringBuffer.append(new String(temp, 0, len));
    }
    //关闭输入流
    input.close();
    return stringBuffer.toString();
}
}

最后是实现效果图:

这里文件使用的模式是私有模式,只能本应用读取还会覆盖原文件,这样就可以实现简单的文件读写。

3、读写SDcard的文件

读写SDCard需要权限:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

对设备读写SDCard的时候需要判断SDCard是否存在,很多手机是不存在SDcard的,下面我们对SDCard的读写中会有体现,下面我们一起通过例子实现SDCard的读写操作

首先是布局文件代码:

<EditText
    android:id="@+id/ed_file_save_sd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp" />

<Button
    android:id="@+id/btn_file_save_sd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="写入到SDcard" />

<Button
    android:id="@+id/btn_file_read_sd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="从SDcard读取" />

<TextView
    android:id="@+id/tv_read_file_sd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:textColor="#000"
    android:textSize="14sp" />

Activity代码:

    ed_file_save_sd = (EditText) findViewById(R.id.ed_file_save_sd);
    tv_read_file_sd = (TextView) findViewById(R.id.tv_read_file_sd);
    btn_file_read_sd = (Button) findViewById(R.id.btn_file_read_sd);
    btn_file_read_sd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                String content = readFromSD();
                tv_read_file_sd.setText("从SDCard读取到的内容是:" + content);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showToast(FileDataActivity.this, "读取文件失败!");
            }
        }
    });
    btn_file_save_sd = (Button) findViewById(R.id.btn_file_save_sd);
    btn_file_save_sd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String content = ed_file_save_sd.getText().toString();
            try {
                save2SDCard(content);
                ToastUtils.showToast(FileDataActivity.this, "文件写入SDCard成功");
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showToast(FileDataActivity.this, "文件写入SDCard失败");
            }
        }
    });

public void save2SDCard(String content) throws Exception {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 如果sdcard存在
        String fileName3 = Environment.getExternalStorageDirectory().getCanonicalPath() + File.separator + "test" + File.separator + fileName2;
        File file = new File(fileName3);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();
    } else {
        ToastUtils.showToast(this, "SDCard不存在");
    }

}
public String readFromSD() throws Exception {
    StringBuffer stringBuffer = new StringBuffer("");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        String fileName3 = Environment.getExternalStorageDirectory().getCanonicalPath() + File.separator + "test" + File.separator + fileName2;
        File file = new File(fileName3);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] temp = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(temp)) > 0) {
            stringBuffer.append(new String(temp, 0, len));
        }
        fileInputStream.close();
    } else {
        ToastUtils.showToast(this, "SDCard不存在");
    }
    return stringBuffer.toString();
}

SDCard的读取和文件操作差不多,需要判断SDCard是否存在,最后是效果图:

4、读取raw和assets文件的数据

  raw/res中的文件会被映射到Android的R文件中,我们直接通过R文件就可以访问,这里就不在过多介绍了。

  assets中的文件不会像raw/res中的文件一样被映射到R文件中,可以有目录结构,Android提供了一个访问assets文件的AssetManager对象,我们访问也很简单:

AssetManager assetsManager =  getAssets();  
InputStream inputStream = assetsManager.open("fileName");

这样就可以直接获取到assets目录下的资源文件。

AndroidOS的文件存储就简单介绍到这里,下一篇我们介绍SharedPreference存储方法,下面提供一些文件存储的工具方法:

package com.example.datasave.io;

import android.content.Context;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * IO流 工具类<br>
 * 很简单,仅支持文本操作
 */
public class IOUtils {

/**
 * 文本的写入操作
 *
 * @param filePath 文件路径。一定要加上文件名字 <br>
 *                 例如:../a/a.txt
 * @param content  写入内容
 * @param append   是否追加
 */
public static void write(String filePath, String content, boolean append) {
    BufferedWriter bufw = null;
    try {
        bufw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filePath, append)));
        bufw.write(content);

    } catch (Exception e1) {
        e1.printStackTrace();
    } finally {
        if (bufw != null) {
            try {
                bufw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 文本的读取操作
 *
 * @param path 文件路径,一定要加上文件名字<br>
 *             例如:../a/a.txt
 * @return
 */
public static String read(String path) {
    BufferedReader bufr = null;
    try {
        bufr = new BufferedReader(new InputStreamReader(
                new FileInputStream(path)));
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = bufr.readLine()) != null) {
            sb.append(str);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bufr != null) {
            try {
                bufr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

/**
 * 文本的读取操作
 *
 * @param is 输入流
 * @return
 */
public static String read(InputStream is) {
    BufferedReader bufr = null;
    try {
        bufr = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = bufr.readLine()) != null) {
            sb.append(str);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bufr != null) {
            try {
                bufr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}


/**
 * @param context  上下文
 * @param fileName 文件名
 * @return 字节数组
 */
public static byte[] readBytes(Context context, String fileName) {
    FileInputStream fin = null;
    byte[] buffer = null;
    try {
        fin = context.openFileInput(fileName);
        int length = fin.available();
        buffer = new byte[length];
        fin.read(buffer);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fin != null) {
                fin.close();
                fin = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return buffer;
}

/**
 * 快速读取程序应用包下的文件内容
 *
 * @param context  上下文
 * @param filename 文件名称
 * @return 文件内容
 * @throws IOException
 */
public static String read(Context context, String filename)
        throws IOException {
    FileInputStream inStream = context.openFileInput(filename);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    byte[] data = outStream.toByteArray();
    return new String(data);
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值