Android--文件保存与读取



作者注:由于我在测试这个功能的时候发现文件名无法使用中文(sdk2.2 + 模拟器),如果有哪为高手无意中浏览此文章后,能对这个问题予以指点,我将感激不尽。呵呵。


********************注: 在Activity中有 getFileDir() 和 getCacheDir(); 方法可以获得当前的手机自带的存储空间中的当前包文件的路径
getFileDir() ----- /data/data/cn.xxx.xxx(当前包)/files
getCacheDir() ----- /data/data/cn.xxx.xxx(当前包)/cache

Java代码   收藏代码
  1. 1. 编写文件读取与写入功能实现类 FileService  
  2.   
  3.     package cn.android.service;  
  4.   
  5.     import java.io.ByteArrayOutputStream;  
  6.     import java.io.FileInputStream;  
  7.     import java.io.FileOutputStream;  
  8.   
  9.     import android.content.Context;  
  10.     import android.util.Log;  
  11.   
  12.     /** 
  13.      * 文件保存与读取功能实现类 
  14.      * @author Administrator 
  15.      * 
  16.      * 2010-6-28 下午08:15:18 
  17.      */  
  18.     public class FileService {  
  19.   
  20.         public static final String TAG = "FileService";  
  21.         private Context context;  
  22.   
  23.         //得到传入的上下文对象的引用  
  24.         public FileService(Context context) {  
  25.             this.context = context;  
  26.         }  
  27.   
  28.         /** 
  29.          * 保存文件 
  30.          *  
  31.          * @param fileName 文件名 
  32.          * @param content  文件内容 
  33.          * @throws Exception 
  34.          */  
  35.         public void save(String fileName, String content) throws Exception {  
  36.   
  37.             // 由于页面输入的都是文本信息,所以当文件名不是以.txt后缀名结尾时,自动加上.txt后缀  
  38.             if (!fileName.endsWith(".txt")) {  
  39.                 fileName = fileName + ".txt";  
  40.             }  
  41.               
  42.             byte[] buf = fileName.getBytes("iso8859-1");  
  43.               
  44.             Log.e(TAG, new String(buf,"utf-8"));  
  45.               
  46.             fileName = new String(buf,"utf-8");  
  47.               
  48.             Log.e(TAG, fileName);  
  49.               
  50.             // Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND  
  51.             // Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。  
  52.             // Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。  
  53.             // MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。  
  54.             // 如果希望文件被其他应用读和写,可以传入:  
  55.             // openFileOutput("output.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);  
  56.   
  57.             FileOutputStream fos = context.openFileOutput(fileName, context.MODE_PRIVATE);  
  58.             fos.write(content.getBytes());  
  59.             fos.close();  
  60.         }  
  61.   
  62.         /** 
  63.          * 读取文件内容 
  64.          *  
  65.          * @param fileName 文件名 
  66.          * @return 文件内容 
  67.          * @throws Exception 
  68.          */  
  69.         public String read(String fileName) throws Exception {  
  70.   
  71.             // 由于页面输入的都是文本信息,所以当文件名不是以.txt后缀名结尾时,自动加上.txt后缀  
  72.             if (!fileName.endsWith(".txt")) {  
  73.                 fileName = fileName + ".txt";  
  74.             }  
  75.   
  76.             FileInputStream fis = context.openFileInput(fileName);  
  77.             ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  78.   
  79.             byte[] buf = new byte[1024];  
  80.             int len = 0;  
  81.   
  82.             //将读取后的数据放置在内存中---ByteArrayOutputStream  
  83.             while ((len = fis.read(buf)) != -1) {  
  84.                 baos.write(buf, 0, len);  
  85.             }  
  86.   
  87.             fis.close();  
  88.             baos.close();  
  89.   
  90.             //返回内存中存储的数据  
  91.             return baos.toString();  
  92.   
  93.         }  
  94.   
  95.     }  
  96.   
  97. 2. 编写Activity类:  
  98.     package cn.android.test;  
  99.   
  100.     import android.app.Activity;  
  101.     import android.os.Bundle;  
  102.     import android.util.Log;  
  103.     import android.view.View;  
  104.     import android.widget.Button;  
  105.     import android.widget.EditText;  
  106.     import android.widget.Toast;  
  107.     import cn.android.service.FileService;  
  108.   
  109.     public class TestAndroidActivity extends Activity {  
  110.         /** Called when the activity is first created. */  
  111.           
  112.         //得到FileService对象  
  113.         private FileService fileService = new FileService(this);  
  114.         //定义视图中的filename输入框对象  
  115.         private EditText fileNameText;  
  116.         //定义视图中的contentText输入框对象  
  117.         private EditText contentText;  
  118.         //定义一个土司提示对象  
  119.         private Toast toast;  
  120.   
  121.           
  122.         @Override  
  123.         public void onCreate(Bundle savedInstanceState) {  
  124.         super.onCreate(savedInstanceState);  
  125.         setContentView(R.layout.main);  
  126.             
  127.         //得到视图中的两个输入框和两个按钮的对象引用  
  128.         Button button = (Button)this.findViewById(R.id.button);  
  129.         Button read = (Button)this.findViewById(R.id.read);  
  130.         fileNameText = (EditText) this.findViewById(R.id.filename);  
  131.         contentText = (EditText) this.findViewById(R.id.content);  
  132.           
  133.         //为保存按钮添加保存事件  
  134.         button.setOnClickListener(new View.OnClickListener() {  
  135.                 @Override  
  136.                 public void onClick(View v) {  
  137.                       
  138.                     String fileName = fileNameText.getText().toString();  
  139.                     String content = contentText.getText().toString();  
  140.                       
  141.                     //当文件名为空的时候,提示用户文件名为空,并记录日志。  
  142.                     if(isEmpty(fileName)) {  
  143.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG);  
  144.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  145.                         toast.show();     
  146.                         Log.w(fileService.TAG, "The file name is empty");  
  147.                         return;  
  148.                     }  
  149.                       
  150.                     //当文件内容为空的时候,提示用户文件内容为空,并记录日志。  
  151.                     if(isEmpty(content)) {  
  152.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_content, Toast.LENGTH_LONG);  
  153.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  154.                         toast.show();     
  155.                         Log.w(fileService.TAG, "The file content is empty");  
  156.                         return;  
  157.                     }  
  158.                       
  159.                     //当文件名和内容都不为空的时候,调用fileService的save方法  
  160.                     //当成功执行的时候,提示用户保存成功,并记录日志  
  161.                     //当出现异常的时候,提示用户保存失败,并记录日志  
  162.                     try {  
  163.                         fileService.save(fileName, content);  
  164.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.success, Toast.LENGTH_LONG);  
  165.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  166.                         toast.show();     
  167.                         Log.i(fileService.TAG, "The file save successful");  
  168.                     } catch (Exception e) {  
  169.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.fail, Toast.LENGTH_LONG);  
  170.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  171.                         toast.show();     
  172.                         Log.e(fileService.TAG, "The file save failed");  
  173.                     }  
  174.                       
  175.                 }  
  176.         });  
  177.           
  178.           
  179.         //为读取按钮添加读取事件  
  180.         read.setOnClickListener(new View.OnClickListener() {  
  181.                 @Override  
  182.                 public void onClick(View v) {  
  183.                       
  184.                     //得到文件名输入框中的值  
  185.                     String fileName = fileNameText.getText().toString();  
  186.                       
  187.                     //如果文件名为空,则提示用户输入文件名,并记录日志  
  188.                     if(isEmpty(fileName)) {  
  189.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG);  
  190.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  191.                         toast.show();     
  192.                         Log.w(fileService.TAG, "The file name is empty");  
  193.                         return;  
  194.                     }  
  195.                       
  196.                     //调用fileService的read方法,并将读取出来的内容放入到文本内容输入框里面  
  197.                     //如果成功执行,提示用户读取成功,并记录日志。  
  198.                     //如果出现异常信息(例:文件不存在),提示用户读取失败,并记录日志。  
  199.                     try {  
  200.                         contentText.setText(fileService.read(fileName));  
  201.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.read_success, Toast.LENGTH_LONG);  
  202.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  203.                         toast.show();     
  204.                         Log.i(fileService.TAG, "The file read successful");  
  205.                     } catch (Exception e) {  
  206.                         toast = Toast.makeText(TestAndroidActivity.this, R.string.read_fail, Toast.LENGTH_LONG);  
  207.                         toast.setMargin(RESULT_CANCELED, 0.345f);                                     
  208.                         toast.show();     
  209.                         Log.e(fileService.TAG, "The file read failed");  
  210.                     }  
  211.                 }  
  212.         });  
  213.           
  214.           
  215.         }  
  216.           
  217.         //编写一个isEmpty方法,判断字符串是否为空  
  218.         private boolean isEmpty(String s) {  
  219.         if(s == null || "".equals(s.trim())) {  
  220.             return true;  
  221.         }  
  222.         return false;  
  223.         }  
  224.           
  225.     }  
  226.   
  227. 3.文件布局文件:main.xml  
  228.     <?xml version="1.0" encoding="utf-8"?>  
  229.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  230.         android:orientation="vertical"  
  231.         android:layout_width="fill_parent"  
  232.         android:layout_height="fill_parent"  
  233.         >  
  234.           
  235.         <TextView    
  236.             android:layout_width="fill_parent"   
  237.             android:layout_height="wrap_content"   
  238.             android:text="@string/filename"  
  239.         />  
  240.           
  241.         <EditText   
  242.             android:layout_width="fill_parent"   
  243.             android:layout_height="wrap_content"   
  244.             android:id="@+id/filename"  
  245.         />  
  246.           
  247.         <TextView    
  248.             android:layout_width="fill_parent"   
  249.             android:layout_height="wrap_content"   
  250.             android:text="@string/content"  
  251.         />  
  252.           
  253.         <EditText   
  254.             android:layout_width="fill_parent"   
  255.             android:layout_height="wrap_content"   
  256.             android:minLines="3"  
  257.             android:id="@+id/content"  
  258.         />  
  259.           
  260.         <LinearLayout  
  261.         android:orientation="horizontal"  
  262.         android:layout_width="fill_parent"  
  263.         android:layout_height="fill_parent">  
  264.           
  265.             <Button   
  266.                 android:layout_width="wrap_content"   
  267.                 android:layout_height="wrap_content"   
  268.                 android:id="@+id/button"  
  269.                 android:text="@string/save"  
  270.             />  
  271.               
  272.             <Button   
  273.                 android:layout_width="wrap_content"   
  274.                 android:layout_height="wrap_content"   
  275.                 android:id="@+id/read"  
  276.                 android:text="@string/read"  
  277.             />  
  278.           
  279.         </LinearLayout>  
  280.           
  281.     </LinearLayout>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值