Android 文件管理方法

Android 文件管理方法 Android使用的是基于Linux的文件系统,对于文件的访问和管理是通过权限设置来限制的. 在Linux系统中,文件权限分别描述了创建者、同组用户和其他用户对文件的操作限制。 x表示可执行,r表示可读,w表示可写,d表示目录,-表示普通文件。 产生这样的文件权限与程序人员设定的 Android 存储文件的类型 (内部存储)程序开发人员可以建立和访问程序自身的私有文件; (资源存储)可以访问保存在资源目录中的原始文件和XML文件; (外部存储)可以在SD卡等外部存储设备中保存文件

Android系统允许应用程序创建仅能够自身访问的私有文件,文件保存在设备的内部存储器上,在Linux系统下的/data/data/<package name>/files目录中 Android系统不仅支持标准Java的IO类和方法,还提供了能够简化读写流式文件过程的函数 FileOutputStream openFileOutput(String filename int mode) FileInputStream openFileInput(String filename) 参数文件不允许包含描述路径的斜杠(其存储位置固定) 访问模式:

MODE_PRIVATE 私有模式,缺陷模式,文件仅能够被文件创建程序访问,或具有相同UID的程序访问。 MODE_APPEND 追加模式,如果文件已经存在,则在文件的结尾处添加新数据。 MODE_WORLD_READABLE 全局读模式,允许任何程序读取私有文件。 MODE_WORLD_WRITEABLE 全局写模式,允许任何程序写入私有文件。

三个基本的读方法

abstract int read() :读取一个字节数据,并返回读到的数据,如果返回-1,表示读到了输入流的末尾。    int read(byte[] b) :将数据读入一个字节数组,同时返回实际读取的字节数。如果返回-1,表示读到了输入流的末尾。    int read(byte[] b, int off, int len) :将数据读入一个字节数组,同时返回实际读取的字节数。如果返回-1,表示读到了输入流的末尾。off指定在数组b中存放数据的起始偏移位置;len指定读取的最大字节数。 其它方法   long skip(long n) :在输入流中跳过n个字节,并返回实际跳过的字节数。   int available() :返回在不发生阻塞的情况下,可读取的字节数。   void close() :关闭输入流,释放和这个流相关的系统资源。   void mark(int readlimit) :在输入流的当前位置放置一个标记,如果读取的字节数多于readlimit设置的值,则流忽略这个标记。   void reset() :返回到上一个标记。   boolean markSupported() :测试当前流是否支持mark和reset方法。如果支持,返回true,否则返回false。

三个基本的写方法

abstract void write(int b) :往输出流中写入一个字节。    void write(byte[] b) :往输出流中写入数组b中的所有字节。    void write(byte[] b, int off, int len) :往输出流中写入数组b中从偏移量off开始的len个字节的数据。 其它方法   void flush() :刷新输出流,强制缓冲区中的输出字节被写出。   void close() :关闭输出流,释放和这个流相关的系统资源。

对文件和流的操作容易引发异常,所以必须要用try-catch语句

主要核心代码

首先是新建一个文件 private final String FILE_NAME = "Myfile01.txt"; 写文件 FileOutputStream fos = null;//声明一个全局变量 //注意下面的语句要进行抛异常处理FileNotFoundException e,IOException e fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE);//写流式文件过程的

函数,这里的权限是私有的 String text = entryText.getText().toString();//把输入的内容转化为字符串 fos.write(text.getBytes());//把转化为字符串的内容转化为字节,然后写入 //下面语句写在finally里面 fos.flush();//把缓存里的内容写入到文件 fos.close();//关闭流

读文件 FileInputStream fis = null;//定义一个全局变量 fis = openFileInput(FILE_NAME);//打开要读取的文件 if (fis.available() == 0){//判断文件是否为空,为空就直接返回  return; } byte[] readBytes = new byte[fis.available()];//把文件里的内容转化为字节 while(fis.read(readBytes) != -1){//读文件,直到读到最后 } String text = new String(readBytes);//把读到的字节转化为字符串

读文件的第二种方法

String path = "/data/data/cn.itcast.file/files/writeable.txt";//得到文件路径   File file = new File(path);//创建一个文件对象   FileInputStream inStream = new FileInputStream(file);//读文件   byte[] buffer = new byte[1024];//缓存   int len = 0;   ByteArrayOutputStream outStream = new ByteArrayOutputStream();   while( (len = inStream.read(buffer))!= -1){//直到读到文件结束    outStream.write(buffer, 0, len);   }   byte[] data = outStream.toByteArray();//得到文件的二进制数据   outStream.close();   inStream.close();   Log.i(TAG, new String(data));

这里列举一个例子,主要是把写入的文件读出来显示在TextView中

第一步,修改布局文件main.xml

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>  2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  3     android:orientation="vertical"  4     android:layout_width="fill_parent"  5     android:layout_height="fill_parent"  6     >  7     <TextView  android:id="@+id/label"  8     android:layout_width="fill_parent"   9     android:layout_height="wrap_content"  10     android:text="@string/hello" 11     /> 12     <EditText android:id="@+id/entry" 13         android:text="输入文件内容"   14         android:layout_width="fill_parent"  15         android:layout_height="wrap_content"> 16     </EditText> 17     <LinearLayout android:id="@+id/LinearLayout01"  18         android:layout_width="wrap_content"  19         android:layout_height="wrap_content"> 20         <Button android:id="@+id/write" 21             android:text="写入文件"   22             android:layout_width="wrap_content"  23             android:layout_height="wrap_content"> 24         </Button> 25         <Button android:id="@+id/read" 26             android:text="读取文件"   27             android:layout_width="wrap_content"  28             android:layout_height="wrap_content"> 29         </Button> 30     </LinearLayout> 31     <CheckBox android:id="@+id/append" 32         android:text="追加模式"   33         android:layout_width="wrap_content"  34         android:layout_height="wrap_content"> 35     </CheckBox> 36     <TextView android:id="@+id/display" 37         android:text="文件内容显示区域"   38         android:layout_width="fill_parent"  39         android:layout_height="fill_parent" 40         android:background="#FFFFFF"  41         android:textColor="#000000" > 42     </TextView> 43 </LinearLayout>
复制代码

第二步:写入核心代码,

复制代码
  1 package cn.edu.zwu.tel;   2    3 import java.io.FileInputStream;   4 import java.io.FileNotFoundException;   5 import java.io.FileOutputStream;   6 import java.io.IOException;   7 import android.app.Activity;   8 import android.content.Context;   9 import android.os.Bundle;  10 import android.view.View;  11 import android.view.View.OnClickListener;  12 import android.widget.Button;  13 import android.widget.CheckBox;  14 import android.widget.EditText;  15 import android.widget.TextView;  16   17 public class FileSaveTest01Activity extends Activity {  18       19     private final String FILE_NAME = "Myfile01.txt";  20     private TextView labelView;  21     private TextView displayView;  22     private CheckBox appendBox ;  23     private EditText entryText;  24     @Override  25     public void onCreate(Bundle savedInstanceState) {  26         super.onCreate(savedInstanceState);  27         setContentView(R.layout.main);  28           29         labelView = (TextView)findViewById(R.id.label);  30         displayView = (TextView)findViewById(R.id.display);  31         appendBox = (CheckBox)findViewById(R.id.append);  32             entryText = (EditText)findViewById(R.id.entry);  33         Button writeButton = (Button)findViewById(R.id.write);  34         Button readButton = (Button)findViewById(R.id.read);  35         writeButton.setOnClickListener(writeButtonListener);  36         readButton.setOnClickListener(readButtonListener);  37         entryText.selectAll();  38         entryText.findFocus();  39     }  40       41       42     OnClickListener writeButtonListener = new OnClickListener() {   43         @Override  44         public void onClick(View v) {  45             FileOutputStream fos = null;      46             try {  47                  if (appendBox.isChecked()){  48                      fos = openFileOutput(FILE_NAME,Context.MODE_APPEND);  49                  }  50                  else {  51                      fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE);  52                  }  53                       54                  String text = entryText.getText().toString();  55                  fos.write(text.getBytes());  56                  labelView.setText("文件写入成功,写入长度:"+text.length());  57                  entryText.setText("");  58             } catch (FileNotFoundException e) {  59                 e.printStackTrace();  60             }  61             catch (IOException e) {  62                 e.printStackTrace();  63             }  64             finally{  65                 if (fos != null){  66                     try {  67                         fos.flush();  68                         fos.close();  69                     } catch (IOException e) {  70                         e.printStackTrace();  71                     }              72                 }  73             }  74         }     75      };  76        77      OnClickListener readButtonListener = new OnClickListener() {   78          @Override  79          public void onClick(View v) {  80              displayView.setText("");  81              FileInputStream fis = null;  82              try {  83                 fis = openFileInput(FILE_NAME);  84                 if (fis.available() == 0){  85                     return;  86                 }  87                 byte[] readBytes = new byte[fis.available()];  88                 while(fis.read(readBytes) != -1){  89                 }  90                 String text = new String(readBytes);  91                 displayView.setText(text);  92                 labelView.setText("文件读取成功,文件长度:"+text.length());  93             } catch (FileNotFoundException e) {  94                 e.printStackTrace();  95             }  96             catch (IOException e) {  97                 e.printStackTrace();  98             }  99               100          }    101       }; 102       103 }
复制代码

效果图:

原文地址:https://www.cnblogs.com/fx2008/p/3137978.html