要求:
输入文件名,文件内容分别存储在手机内存和外存中,并且都可以读去取出来。
步骤:
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(),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实现文件存储并读取的示例代码全部内容,希望文章能够帮你解决Android实现文件存储并读取的示例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)