欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-20 13:15:22
要求: 输入文件名,文件内容分别存储在手机内存和外存中,并且都可以读去取出来。 步骤: 1.创建一个名为cdsavefile的android项目...

要求:

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

步骤:

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.项目部署在模拟器上:

进入程序后:

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

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

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

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

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

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

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

上一篇:

下一篇: