Android File存储

原创文章,转载请注明出处:http://www.cnblogs.com/baipengzhan/p/Android_File_store.html                      

一 概念

Android系统中提供了一种文件读写的方法,可以将一些数据以文件的形式保存在设备中。比如一些word文档,PDF文档,图片,音频,视频文件等。文件会保存在/data/data/<packagename>/files中。文件存储数据使用了Java中的IO操作来进行文件的保存和读取,AndroidContext类中封装好了输入流和输出流的获取方法,我们使用这些封装好的方法进行文件的增删改查等操作,注意使用方法是在有上下文的环境中使用。

二 使用

1,        保存文件

保存文件需要获取输出流,将要保存的内容写入到我们自己规定文件名的文件中,方法如下:

FileOutputStream openFileOutput = openFileOutput(prefes1, prefes2);

获得输出流后,便可以将我们获取的文件直接写入,方法的第一个参数是我们要保存的文件名,注意文件的格式需要我们自己定义,即要写上后缀,这点不同于SharedPreferences保存数据自动生成Xml格式,需要注意。第二个参数是写入模式,共有以下几种:

Context.MODE_PRIVATE 为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下写入的内容会覆盖原文件的内容。
Context.MODE_APPEND 检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_WORLD_READABLE 表示当前文件可以被其他应用读取。
MODE_WORLD_WRITEABLE 表示当前文件可以被其他应用写入。
在使用模式时,可以用"+"来选择多种模式,比如openFileOutput(FILENAME, Context.MODE_PRIVATE + MODE_WORLD_READABLE);

2,           读取文件

可以使用系统提供的方法获取输出流实现读取,方法如下:

FileInputStream openFileInput = openFileInput(prefes);

其中的参数填入要读取的文件名

3,           删除文件

deleteFile(prefes);

其中的参数为要删除的文件名 

4,           获取文件路径方法:
绝对路径:/data/data/<package name>/files/filename
Context:Context.getFilesDir()可以获取到"/data/data/<package name>/files"

三 Android实例

1,布局和功能

①布局

布局如下图所示:

 ②功能

(以下描述控件的顺序按照上图的由上到下顺序)

保存文件功能:第一个EditText中写入要保存的内容,第二个EditText中写入要保存的文件名(注意加后缀),点击第一个按钮保存文件

读取文件内容功能:第三个EditText中写入要读取的文件名,点击第二个按钮,在第一个TextView中显示文件的内容

删除文件功能:在第四个EditText中写入要删除的文件名,点击第三个按钮,删除文件

2,主要代码

①MainActivity.java

package com.example.filestore;

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

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

public class MainActivity extends Activity {

    private EditText et_save;
    private TextView tv_read;
    private EditText et_save_filename;
    private EditText et_read_filename;
    private EditText et_delete_filename;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_save = (EditText) findViewById(R.id.et_save);
        tv_read = (TextView) findViewById(R.id.tv_read);
        et_save_filename = (EditText) findViewById(R.id.et_save_filename);
        et_read_filename = (EditText) findViewById(R.id.et_read_filename);
        et_delete_filename = (EditText) findViewById(R.id.et_delete_filename);
    }

    //设置保存点击事件
    public void save(View v) {
        //获得输入框中的内容
        
        //非空判断
        if(et_save.getText() == null || et_save.getText().length() <= 0 || et_save_filename.getText() == null || et_save_filename.getText().length() <= 0) {
            Toast.makeText(getApplicationContext(), "文件名和输入内容不能为空", Toast.LENGTH_SHORT).show();
        }else {
            //获取待保存的文件名和保存内容
            String content_save = et_save.getText().toString().trim();
            String filename_save = et_save_filename.getText().toString().trim();
            try {
                //获取输出流
                FileOutputStream openFileOutput = openFileOutput(filename_save, MODE_PRIVATE);
                //使用输出流向文件中写入数据
                openFileOutput.write(content_save.getBytes());
                //关闭输出流
                openFileOutput.close();
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        
    }
    //设置读取点击事件
    public void read(View v) {
        //首先清空上次残留的内容
        tv_read.setText("");
        //获取要读取的文件名
        //非空判断
        if(et_read_filename.getText() == null || et_read_filename.getText().length() <= 0) {
            Toast.makeText(getApplicationContext(), "要读取的文件名不能为空", Toast.LENGTH_SHORT).show();
        }else {
            String filename_read = et_read_filename.getText().toString().trim();
            
            try {
                //获取输入流
                FileInputStream openFileInput = openFileInput(filename_read);
                //开始读取数据,为了展示内容使用内存输出流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buffer = new byte[1024];
                while((len = openFileInput.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                //读取完毕,关流
                openFileInput.close();                
                //将内存输出流中的数据显示到界面上
                tv_read.setText(baos.toString());
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //此处提示未找到文件
                Toast.makeText(getApplicationContext(), "未找到文件", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
        
    }
    //设置删除点击事件
    public void delete(View v) {
        //首先获取要删除的文件名
        //非空判断
        if(et_delete_filename.getText() == null || et_delete_filename.getText().length() <= 0) {
            Toast.makeText(getApplicationContext(), "要删除的文件名不能为空", Toast.LENGTH_SHORT).show();
        }else {
            //获取要删除的文件名
            String filename_delete = et_delete_filename.getText().toString().trim();
            //删除数据
            deleteFile(filename_delete);
        }
        
    }
}

 ②activity_main.xml

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="right"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:text="@string/tv_hint"
        />
    <EditText
        android:id="@+id/et_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="12sp"
         />
     <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_hint2"
        />
     <EditText
        android:id="@+id/et_save_filename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="12sp"
         />     
    <Button 
        android:id="@+id/bt_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="save"
        android:textSize="12sp"
        android:text="@string/text_bt_save"
        />
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_hint3"
        />
     <EditText
        android:id="@+id/et_read_filename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="12sp"
         /> 
    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"        
        >        
         <TextView
        android:id="@+id/tv_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/text_read" />
        
    </ScrollView>
   
    <Button 
        android:id="@+id/bt_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:onClick="read"
        android:text="@string/text_bt_read"
        />
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_hint4"
        />
     <EditText
        android:id="@+id/et_delete_filename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="12sp"
         /> 
    <Button 
        android:id="@+id/bt_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:onClick="delete"
        android:text="@string/text_bt_delete"
        />

</LinearLayout>
原文地址:https://www.cnblogs.com/baipengzhan/p/Android_File_store.html