您的位置:首页 > 移动开发 > Android开发

Android实现文件存储并读取的示例代码

2017-01-27 11:15 585 查看

要求:

输入文件名,文件内容分别存储在手机内存和外存中,并且都可以读去取出来。

步骤:

1.创建一个名为CDsaveFile的Android项目

2.编写布局文件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:orientation="vertical"
tools:context="hhh.exercise.cdsavefile.MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textView_inputFileName"
android:textColor="#00ff00"
android:textSize="26sp" />
<EditText
android:id="@+id/editView_fileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="@string/editView_fileName"
android:maxLines="1"
android:textColor="#ff0000"
android:textSize="26sp" />
<requestFocus />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/textView_inputFileContent"
android:textColor="#00ff00"
android:textSize="26sp" />
<EditText
android:id="@+id/editView_fileContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="@string/editView_fileContent"
android:maxLines="2"
android:minLines="2"
android:textColor="#ff0000"
android:textSize="26sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button_saveToPhone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/button_saveToPhone"
android:textColor="#ff00ff"
android:textSize="24sp" />
<Button
android:id="@+id/button_readFromPhone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/button_readFromPhone"
android:textColor="#00ffff"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button_saveToSD"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/button_saveToSD"
android:textColor="#ff00ff"
android:textSize="24sp" />
<Button
android:id="@+id/button_readFromSD"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/button_readFromSD"
android:textColor="#00ffff"
android:textSize="24sp" />
</LinearLayout>
<EditText
android:id="@+id/editText_showResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="3"
android:minLines="3"
android:hint="@string/editText_showResult"
android:textColor="#cccc00"
android:textSize="30sp" />
</LinearLayout>

3.编写主活动中代码MainActivity.Java:

package hhh.exercise.cdsavefile;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import hhh.exercise.service.FileService;
public class MainActivity extends Activity implements OnClickListener {
private EditText editView_fileName;
private EditText editView_fileContent;
private EditText editText_showResult;
private FileService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// 实例化 FileService 类,该类用于处理按钮触发的事件的具体操作
service = new FileService(getApplicationContext());
// 获取布局中的控件
editView_fileName = (EditText) findViewById(R.id.editView_fileName);
editView_fileContent = (EditText) findViewById(R.id.editView_fileContent);
editText_showResult = (EditText) findViewById(R.id.editText_showResult);
// 获取按钮并创建触发事件
((Button) findViewById(R.id.button_saveToPhone)).setOnClickListener(this);
((Button) findViewById(R.id.button_readFromPhone)).setOnClickListener(this);
((Button) findViewById(R.id.button_saveToSD)).setOnClickListener(this);
((Button) findViewById(R.id.button_readFromSD)).setOnClickListener(this);
}
/**
* 为每一个按钮创建触发的事件
*
* @param v触发事件的View对象
*/
@Override
public void onClick(View v) {
String fileName = editView_fileName.getText().toString();
String fileContent = editView_fileContent.getText().toString();
// 判断文件名,文件名要求不为空
if (fileName == null || "".equals(fileName.trim())) {
Toast.makeText(getApplicationContext(), R.string.toast_missFileName, 0).show();
} else {
// 输入的文件名不为空,对每个按钮的触发事件进行处理
String result = null;
switch (v.getId()) {
case R.id.button_saveToPhone:
try {
// 存储文件到手机上
service.saveToPhone(fileName, fileContent);
// 清空内容输入框
editView_fileContent.setText("");
Toast.makeText(getApplicationContext(), R.string.toast_saveToPhone_success, 0).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_saveToPhone_fail, 0).show();
e.printStackTrace();
}
break;
case R.id.button_readFromPhone:
try {
// 读取手机文件中的内容
result = service.readFromPhone(fileName);
// 将内容显示在空间中
editText_showResult.setText(result);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_readFromPhone_fail, 0).show();
e.printStackTrace();
}
break;
case R.id.button_saveToSD:
// 判断sd卡是否存在,并且可以使用,空间足够
int flag = judgeSD();
if (flag == 0 || flag == 1) {
Toast.makeText(getApplicationContext(), R.string.toast_noSD, 0).show();
} else {
try {
service.saveToSD(fileName, fileContent);
editView_fileContent.setText("");
Toast.makeText(getApplicationContext(), R.string.toast_saveToSD_success, 0).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_saveToSD_fail, 0).show();
e.printStackTrace();
}
}
break;
case R.id.button_readFromSD:
// 判断SD卡能够读取
int flag2 = judgeSD();
if (flag2 != 0) {
try {
result = service.readFromSD(fileName);
editText_showResult.setText(result);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_readFromSD_fail, 0).show();
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), R.string.toast_noSD, 0).show();
}
break;
default:
break;
}
}
}
/**
* 判断SD卡是否存在,并且可以读写,空间足够。
*
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private int judgeSD() {
int flag = 0;
// SD卡存在且可以读取
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// 获取SD卡的路劲
String path = Environment.getExternalStorageDirectory().getPath();
// 调用C的类库
StatFs fs = new StatFs(path);
long availabeBolocks = 0;
long bolockSize = 0;
// 为了兼容低版本,所以获取当前应用所在系统的版本号,进而判断
// 分为两种。版本低于4.3的和高于等于4.3的(4.3的版本等级为18)
if (Build.VERSION.SDK_INT >= 18) {
// 获取可用的块
availabeBolocks = fs.getAvailableBlocksLong();
// 获取每个块的大小
bolockSize = fs.getBlockSizeLong();
} else {
// 获取可用的块
availabeBolocks = fs.getAvailableBlocks();
// 获取每个块的大小
bolockSize = fs.getBlockSize();
}
// 计算sd卡可用空间的大小(单位用MB)
long availableByte = availabeBolocks * bolockSize;
float availableMB = (float) availableByte / 1024 / 1024;
// 空间小于1MB,不允许写入数据(实际上时空间小于写入文件的大小,就不允许写入,这里时认为文件大小为1MB)
if (availableMB < 1) {
flag = 1;
} else {
flag = 2;
}
return flag;
} else {
return flag;
}
}
}

其中主活动中FileService类是用来处理按钮点击后的事务的具体操作的。代码如下:

package hhh.exercise.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.content.Context;
import android.os.Environment;
/**
* @author HHH
*
*/
public class FileService {
public Context context;
public FileService(Context context) {
super();
this.context = context;
}
/**
* 保存文件到手机内存中
*
* @param fileName
* @param fileContent
* @return
* @throws Exception
*/
public void saveToPhone(String fileName, String fileContent) throws Exception {
OutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(fileContent);
bufferedWriter.close();
}
/**
* 从手机中读取文件
*
* @param fileName
* @return
* @throws Exception
*/
public String readFromPhone(String fileName) throws Exception {
StringBuilder sBuilder = new StringBuilder();
InputStream inputStream = context.openFileInput(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sBuilder.append(line);
}
bufferedReader.close();
return sBuilder.toString();
}
/**
* 把输入的内容存入到SD卡中
*
* @param fileName
* @param fileContent
* @throws Exception
*/
public void saveToSD(String fileName, String fileContent) throws Exception {
// 获取sd卡的路径
String path = Environment.getExternalStorageDirectory().getPath();
File file = new File(path, fileName);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write(fileContent);
bufferedWriter.close();
}
/**
* 从sd卡中读取文件
*
* @param fileContent
* @return
* @throws Exception
*/
public String readFromSD(String fileName) throws Exception {
StringBuilder sBuilder = new StringBuilder();
String path = Environment.getExternalStorageDirectory().getPath();
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(path, fileName)));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sBuilder.append(line);
}
bufferedReader.close();
return sBuilder.toString();
}
}

strings.xml的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">CDsaveFile</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="textView_inputFileName">请输入文件名</string>
<string name="editView_fileName">FileName</string>
<string name="textView_inputFileContent">请输入文件内容</string>
<string name="editView_fileContent">FileContent</string>
<string name="button_saveToPhone">存到手机</string>
<string name="button_saveToSD">存到SD卡</string>
<string name="button_readFromPhone">读取手机</string>
<string name="button_readFromSD">读取SD</string>
<string name="editText_showResult">Here is the result of the reading</string>
<string name="toast_missFileName">请输入文件名,文件名不可为空</string>
<string name="toast_saveToPhone_success">存储到手机成功</string>
<string name="toast_saveToPhone_fail">存储到手机失败啦......</string>
<string name="toast_saveToSD_success">存储到SD成功</string>
<string name="toast_saveToSD_fail">存储到SD失败啦......</string>
<string name="toast_noSD">sd不存在或空间不足</string>
<string name="toast_readFromPhone_fail">无法读取手机文件</string>
<string name="toast_readFromSD_fail">无法读取SD文件</string>
</resources>

4.在AndroidManifest.xml添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

5.项目部署在模拟器上:

进入程序后:

把文件存储到手机上并读取:

 

把文件存储到SD上并读取:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 文件存储