Android实现文件存储并读取的示例代码
要求:
我们提供的服务有:成都网站设计、成都网站建设、外贸网站建设、微信公众号开发、网站优化、网站认证、丘北ssl等。为超过千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的丘北网站制作公司
输入文件名,文件内容分别存储在手机内存和外存中,并且都可以读去取出来。
步骤:
1.创建一个名为CDsaveFile的Android项目
2.编写布局文件activity_main.xml:
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"?>CDsaveFile Hello world! Settings 请输入文件名 FileName 请输入文件内容 FileContent 存到手机 存到SD卡 读取手机 读取SD Here is the result of the reading 请输入文件名,文件名不可为空 存储到手机成功 存储到手机失败啦...... 存储到SD成功 存储到SD失败啦...... sd不存在或空间不足 无法读取手机文件 无法读取SD文件
4.在AndroidManifest.xml添加权限
5.项目部署在模拟器上:
进入程序后:
把文件存储到手机上并读取:
把文件存储到SD上并读取:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
当前标题:Android实现文件存储并读取的示例代码
文章分享:http://azwzsj.com/article/pdedci.html