广告
返回顶部
首页 > 资讯 > 移动开发 >Android实现文件存储并读取的示例代码
  • 766
分享到

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

示例存储Android 2022-06-06 04:06:05 766人浏览 独家记忆
摘要

要求: 输入文件名,文件内容分别存储在手机内存和外存中,并且都可以读去取出来。 步骤: 1.创建一个名为CDsaveFile的Android项目 2.编写布局文件a

要求:

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

步骤:

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);
 }
 
 @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;
  }
 }
 }
 
 @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;

public class FileService {
 public Context context;
 public FileService(Context context) {
 super();
 this.context = context;
 }
 
 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();
 }
 
 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();
 }
 
 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();
 }
 
 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数据存储之Android 6.0运行时权限下文件存储的思考android数据存储之文件存储方法Android学习之文件存储读取详解Android文件存储实例详解Android文件存储数据方式Android编程之SharedPreferences文件存储操作实例分析android开发基础教程—文件存储功能实现Android 文件存储及常见问题解决


--结束END--

本文标题: Android实现文件存储并读取的示例代码

本文链接: https://www.lsjlt.com/news/22484.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作