Welcome

首页 / 移动开发 / Android / Android学习之文件存储读取

前言
相信大家都知道知道,在AndroidOS中,提供了五中数据存储方式,分别是:ContentProvider存储、文件存储、SharedPreference存储、SQLite数据库存储、网络存储。那么这一篇,我们介绍文件存储。
1.Android文件的操作模式
学过Java的同学都知道,我们新建文件,然后就可以写入数据了,但是Android却不一样,因为Android是 基于Linux的,我们在读写文件的时候,还需加上文件的操作模式,Android中的操作模式如下:


2、文件的操作模式
我们在学Java的时候都知道,Java中的IO操作来进行文件的保存和读取,Android是基于Linux的,与Java不同的是Android在Context类中封装好了输入流和输出流的获取方法,分别是: FileInputStream openFileInput(String name); FileOutputStream(String name , int mode),这两个方法第一个参数 用于指定文件名,第二个参数指定打开文件的模式。Android提供的文件模式有:
1.MODE_PRIVATE:Android提供的默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容。
2.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
3.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
4.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
此外,Android还提供了其它几个重要的文件操作的方法:
1.getDir(String name , int mode):在应用程序的数据文件夹下获取或者创建name对应的子目录
2.File getFilesDir():获取app的data目录下的绝对路径
3.String[] fileList():返回app的data目录下数的全部文件
4.deleteFile(String fileName):删除app的data目录下的指定文件
3、读写文件
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"><EditTextandroid:id="@+id/ed_file_save"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn_file_save"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="保存内容" /><Buttonandroid:id="@+id/btn_file_read"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="读取内容" /><TextViewandroid: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";@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic 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();}}
最后是实现效果图:


这里文件使用的模式是私有模式,只能本应用读取还会覆盖原文件,这样就可以实现简单的文件读写。
4、读写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的读写操作
首先是布局文件代码:
<EditTextandroid:id="@+id/ed_file_save_sd"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20dp" /><Buttonandroid:id="@+id/btn_file_save_sd"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="写入到SDcard" /><Buttonandroid:id="@+id/btn_file_read_sd"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="从SDcard读取" /><TextViewandroid: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() {@Overridepublic 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() {@Overridepublic 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是否存在,最后是效果图:


5、读取raw和assets文件的数据
raw/res中的文件会被映射到Android的R文件中,我们直接通过R文件就可以访问,这里就不在过多介绍了。
assets中的文件不会像raw/res中的文件一样被映射到R文件中,可以有目录结构,Android提供了一个访问assets文件的AssetManager对象,我们访问也很简单:

AssetManager assetsManager = getAssets(); InputStream inputStream = assetsManager.open("fileName");
这样就可以直接获取到assets目录下的资源文件。
AndroidOS的文件存储就简单介绍到这里,下面提供一些文件存储的工具方法:
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);}}
好的,关于Android的数据存储与访问的文件读写就到这里,如果在学习本文中遇到什么问题,或者觉得有些纰漏的地方,欢迎提出,万分感激,谢谢~