概念:
inputStream:将文件中的内容输入到Stream中
outputStream:将Stream中的内容输出到文件中
两个方法:
openFileOutput(String name,int mode):如果文件不存在,Android会自动创建它,创建的目录保存在/data/data/<package_name>/files目录下
openFileInput(String name)
Mode:
MODE_APPEND:如果文件中已经存在内容,则在内容末尾追加
MODE_PRIVATE:文件仅能被该程序访问
MODE_WORLD_READABLE:文件允许被其它应用程序读
MODE_WORLD_WRITEABLE:文件允许被其它应用程序写
MODE_WORLD_READABLE+MODE_WORLD_WRITEABLE :文件允许被其它应用程序读和写
1. Android的文件读写与JavaSE的文件读写相同,都是使用IO流。而且Android使用的正是JavaSE的IO流,下面我们通过一个练习来学习Android的文件读写。
2.编辑strings.xml中的内容如下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Data_FileActivity!</string>
<string name="app_name">Data_File</string>
<string name="file_name">文件名</string>
<string name="file_content">文件内容</string>
<string name="button_file_save">保存</string>
<string name="button_file_read">读取</string>
<string name="file_save_success">保存文件成功</string>
<string name="file_save_failed">保存文件失败</string>
<string name="file_read_failed">读取文件失败</string>
</resources>
3.编辑main.xml中的内容如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 文件名 -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/file_name" />
<EditText android:layout_width="fill_parent"
android:inputType="text"
android:layout_height="wrap_content" android:id="@+id/et_file_name" />
<!-- 文件内容 -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/file_content" />
<EditText android:layout_width="fill_parent"
android:inputType="text"
android:layout_height="wrap_content" android:minLines="3"
android:id="@+id/et_file_content" />
<!-- 保存和读取按钮,采用相对布局 -->
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- 保存按钮 -->
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/button_file_save"
android:id="@+id/bt_save" />
<!-- 读取按钮 -->
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@id/bt_save"
android:text="@string/button_file_read" android:id="@+id/bt_read" />
</RelativeLayout>
</LinearLayout>
4.添加java代码
Android建议采用MVC开发模式,所以我们在Android应用开发中最好使用MVC设计模式。MVC设计模式使三层分离,从而很好的解耦,何乐而不为。
首先我们向工程中添加一个FileService.java:
package wei.cao.file.service;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
public class FileService {
Context context;
public FileService(Context context) {
super();
this.context = context;
}
public void save(String fileName,String fileContent) throws Exception
{
FileOutputStream fileOutputStream=this.context.openFileOutput(fileName,Context.MODE_PRIVATE);
fileOutputStream.write(fileContent.getBytes());
}
public String read(String fileName) throws Exception
{
FileInputStream fileInputStream=this.context.openFileInput(fileName);
ByteArrayOutputStream byteArray=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=fileInputStream.read(buffer))>0)
{
byteArray.write(buffer, 0, len);
}
return byteArray.toString();
}
}
5.然后再向工程中添加FileButtonOnClickEvent.java:
package wei.cao.file.event;
import wei.cao.data.R;
import wei.cao.file.service.FileService;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class FileButtonOnClickEvent implements OnClickListener{
private Activity activity;
private FileService fileService;
private static final String TAG="FileButtonOnClickEvent";
public FileButtonOnClickEvent(Activity activity) {
super();
this.activity = activity;
this.fileService = new FileService(activity);
}
@Override
public void onClick(View v) {
Button button=(Button)v;
switch(button.getId())
{
case R.id.bt_save:
EditText etFileNameS=(EditText)this.activity.findViewById(R.id.et_file_name);
String strFileNameS=etFileNameS.getText().toString();
EditText etFileContentS=(EditText)this.activity.findViewById(R.id.et_file_content);
String strFileContentS=etFileContentS.getText().toString();
try
{
this.fileService.save(strFileNameS, strFileContentS);
Toast.makeText(this.activity, R.string.file_save_success, 1).show();
Log.i(TAG, "save file success");
}
catch(Exception e)
{
Toast.makeText(this.activity, R.string.file_save_failed, 1).show();
Log.e(TAG, e.toString());
}
break;
case R.id.bt_read:
EditText etFileNameR=(EditText)this.activity.findViewById(R.id.et_file_name);
String strFileNameR=etFileNameR.getText().toString();
try{
String strResult=this.fileService.read(strFileNameR);
EditText etFileContentR=(EditText)this.activity.findViewById(R.id.et_file_content);
etFileContentR.setText(strResult);
Log.i(TAG, "read file success");
}
catch(Exception e)
{
Toast.makeText(this.activity, R.string.file_read_failed, 1).show();
Log.e(TAG, e.toString());
}
break;
default:
break;
}
}
}
6.最后编辑Data_FileActivity.java中的内容
package wei.cao.data;
import wei.cao.file.event.FileButtonOnClickEvent;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class Data_FileActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonRead=(Button)this.findViewById(R.id.bt_read);
Button buttonSave=(Button)this.findViewById(R.id.bt_save);
FileButtonOnClickEvent filebuttonOnClickEvent=new FileButtonOnClickEvent(this);
buttonRead.setOnClickListener(filebuttonOnClickEvent);
buttonSave.setOnClickListener(filebuttonOnClickEvent);
}
}
7.运行程序
启动模拟器,部署我们的程序。输入文件名和文件内容,点击保存。文件被保存在Android的什么位置?我们知道Android是基于Linux实现的。所以它的根目录是”/”,我们的文件被保存在”/data/data/com.changcheng.file/files”目录下。
我们也可以通过菜单Windows->Show View->Other...->Android->File Explorer,打开 File Explorer面板。通过它可以查看Android的目录结构:
data:应用数据,我们保存的文件在/data/data/packagename/files。
sdcard:现在的手机一般都可以外插一个SD卡,这个目录就是SDCard的目录。操作此目录时需要在主配置文件中注册操作权限。
system:Android操作系统的文件,我们不要修改。
我们可以点击 File Explorer右上角的“软盘向左箭头”图标,导出文件。
8.他程序获取文件路径的方法
1.绝对路径:/data/data/packagename/files/filename;
2.context:context.getFilesDir()+”/filename”;
缓存目录:/data/data/packagename/Cache或getCacheDir();
如果文件过大就不能存放在手机的文件目录,需要存储到SDCard上。
SDCard目录:/sdcard/或Environment.getExternalStorageDirectory()
使用SDCard目录前,需要判断是否有sdcard:Environment.getExternalStorageState()。操作此目录时需要在主配置文件中注册操作权限。
总结:文件名中可以输入.txt,.doc类型的文件,导出即可看到内容