使用SharedPreferences可以方便的完成数据的存储功能,但是其只能保存一些很简单的数据,如果想存储更多的数据,则需要使用文件存储操作。对于文件的存储操作,在Android中有两种形式:
注意:程序中依然使用前面文章所述的Intent实现Activity的调转显示文件中信息
形式一:直接利用Activity提供的文件操作方法。此类操作的所有文件路径只能是“\data\data\<package name>\files\文件名称”。
跳转Activity(FileOperate--->ShowOperate)
源文件及截图:
activity_save.xml
<RelativeLayout 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"
tools:context="cn.lh.filedata.FileOperate" >
<Button
android:id="@+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/savebtn" />
<Button
android:id="@+id/showbtn"
android:layout_toRightOf="@id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/showbtn" />
</RelativeLayout>
activity_load.xml
<RelativeLayout 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"
tools:context="cn.lh.filedata.ShowOperate" >
<TextView
android:id="@+id/msg"
android:textSize="22sp"
android:textColor="#ff00ff"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
FileOperate.java
package cn.lh.filedata;
import java.io.FileOutputStream;
import java.io.PrintStream;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FileOperate extends Activity {
private static final String FileName = "lh.txt";
private Button savebtn = null;
private Button showbtn = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
savebtn = (Button)findViewById(R.id.savebtn);
savebtn.setOnClickListener(new saveListener());
showbtn = (Button)findViewById(R.id.showbtn);
showbtn.setOnClickListener(new showListener());
}
public class saveListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//文件输出流
FileOutputStream output = null;
try {
output = openFileOutput(FileName, MODE_PRIVATE);
} catch (Exception e) {
e.printStackTrace();
}
PrintStream out = new PrintStream(output);
out.println("姓名:Norysn;");
out.println("年龄:26;");
out.println("地址:安徽合肥");
out.close();
}
}
public class showListener implements OnClickListener{
@Override
public void onClick(View v) {
//实现Activity的跳转
Intent intent = new Intent();
intent.setClass(FileOperate.this, ShowOperate.class);
startActivity(intent);
}
}
}
ShowOperate.java
package cn.lh.filedata;
import java.io.FileInputStream;
import java.util.Scanner;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ShowOperate extends Activity {
private static final String FileName = "lh.txt";
private TextView msg = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_load);
msg = (TextView)findViewById(R.id.msg);
//文件输入流
FileInputStream input = null;
try {
//找到指定的文件输入流对象
input = openFileInput(FileName);
} catch (Exception e) {
e.printStackTrace();
}
//定义Scanner
Scanner scan = new Scanner(input);
while(scan.hasNext()){
msg.append(scan.next()+"\n");
}
//关闭输入流
scan.close();
}
}
形式二:利用JavaIO流执行操作。此类操作的文件可以是任意路径(包括sdcard)下,但是需要为其操作授权。
跳转Activity(FileIoOperate-->ShowData)
源文件及截图
activity_save.xml
<RelativeLayout 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"
tools:context="cn.norysn.iosave.FileIoOperate" >
<Button
android:id="@+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/savebtn" />
<Button
android:id="@+id/showbtn"
android:layout_toRightOf="@id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/showbtn" />
</RelativeLayout>
activity_show.xml
<RelativeLayout 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"
tools:context="cn.norysn.iosave.ShowData" >
<TextView
android:id="@+id/msg"
android:textSize="22sp"
android:textColor="#ff00ff"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
FileIoOperate.java
package cn.norysn.iosave;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class FileIoOperate extends Activity {
private Button savebtn = null;
private Button showbtn = null;
//保存文件
private static final String FILENAME = "iodata.txt";
//保存文件夹
private static final String DIR = "/iodata/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
savebtn = (Button)findViewById(R.id.savebtn);
savebtn.setOnClickListener(new btnListener());
showbtn = (Button)findViewById(R.id.showbtn);
showbtn.setOnClickListener(new btnListener());
}
public class btnListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.savebtn:
save();
break;
case R.id.showbtn:
IntentActivity();
break;
}
}
}
public void save(){
//判断SD卡是否存在
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//定义File类对象
File file = new File(Environment.getExternalStorageDirectory().toString()
+DIR+FILENAME);
//判断文件是否存在,如果不存在,则创建
if(!(file.getParentFile().exists())){
//创建文件夹
file.getParentFile().mkdirs();
}
//打印流输入对象
PrintStream out = null;
try {
//追加文件
out = new PrintStream(new FileOutputStream(file,true));
//String str = "作者:By Norysn";
out.println("author:By Norysn");
out.println("age:26");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(out != null){
//关闭打印流
out.close();
}
}
}else{
Toast.makeText(this, "保存失败,SD卡不存在", Toast.LENGTH_SHORT).show();
}
}
public void IntentActivity(){
//实现Activity调转显示
Intent intent = new Intent();
intent.setClass(FileIoOperate.this, ShowData.class);
startActivity(intent);
}
}
ShowData.java
package cn.norysn.iosave;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
public class ShowData extends Activity {
private TextView msg = null;//文本显示
//保存文件
private static final String FILENAME = "iodata.txt";
//保存文件夹
private static final String DIR = "/iodata/";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_show);
msg = (TextView)findViewById(R.id.msg);
show();
}
public void show(){
//判断SD卡是否存在,如果不存在则Toast提示
if(Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)){
//创建File对象
File file = new File(Environment.getExternalStorageDirectory().toString()
+DIR+FILENAME);
//判断文件夹是否存在,不存在则创建文件
if(!(file.getParentFile().exists())){
file.getParentFile().mkdirs();
}
//扫描输入流
//Scanner scan = null;
BufferedReader br = null;
try {
//实例化Scanner
// scan = new Scanner(new FileInputStream(file));
// while(scan.hasNext()){//循环读取
// msg.append(scan.next()+"\n");
// }
InputStreamReader in = new InputStreamReader(new FileInputStream(file));
//实例化BufferReader对象
br = new BufferedReader(in);
String str = null;
while((str=br.readLine()) != null){
msg.append(str+"\n");
//msg.setText(str);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭输入流
// if(scan != null){
// scan.close();
// }
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else{
Toast.makeText(this, "保存失败,SD卡不存在", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.norysn.iosave"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".FileIoOperate"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ShowData"></activity>
</application>
</manifest>