andriod学习——Content的openFileOutput 和 openFileInput操作文件

来源:互联网 发布:朱莉德尔佩 知乎 编辑:程序博客网 时间:2024/06/05 09:27
[java] view plaincopy
  1. package demo.filerw.service;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7.   
  8. import android.content.Context;  
  9. import android.os.Environment;  
  10.   
  11. /** 
  12.  * 文件操作类 
  13.  * @author janrone 
  14.  * @website http://hujl.sinaapp.com 
  15.  */  
  16. public class FileService {  
  17.   
  18.     private Context context;  
  19.       
  20.     public FileService(Context context) {  
  21.         this.context = context;  
  22.     }  
  23.   
  24.     //存储数据到文件  
  25.     public void saveName(String name) throws Exception{  
  26.         //context.getFilesDir();// 得到存放文件的系统目录 /data/data/<package name>/files  
  27.         //context.getCacheDir(); //缓存目录  /data/data/<package name>/cache  
  28.         FileOutputStream outputStream=context.openFileOutput("deomfilerw.txt", Context.MODE_APPEND);  
  29.         outputStream.write(name.getBytes());  
  30.         outputStream.close();  
  31.     }  
  32.     //存储数据到sdcard  
  33.     public void saveNameToSDCard(String name) throws Exception{  
  34.         Environment.getExternalStorageDirectory(); //得到sdcard目录  
  35.         File file=new File("/sdcard","demosdcard.txt");  
  36.         FileOutputStream outputStream=new FileOutputStream(file);  
  37.         outputStream.write(name.getBytes());  
  38.         outputStream.close();  
  39.     }  
  40.       
  41.     // 读取数据  
  42.     public String getName() throws Exception{  
  43.         FileInputStream inputStream=context.openFileInput("deomfilerw.txt");  
  44.         ByteArrayOutputStream outStream=new ByteArrayOutputStream();  
  45.         byte[] buffer=new byte[1024];  
  46.         int len=0;  
  47.         while ((len=inputStream.read(buffer))!=-1){  
  48.             outStream.write(buffer, 0, len);  
  49.         }  
  50.         outStream.close();  
  51.         byte[] data=outStream.toByteArray();  
  52.         String name=new String(data);  
  53.         return name;  
  54.     }  
  55. }  

事件监听类可以放到外边 

[java] view plaincopy
  1. package demo.filerw.clicklistener;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.EditText;  
  8. import android.widget.TextView;  
  9. import android.widget.Toast;  
  10. import demo.filerw.R;  
  11. import demo.filerw.service.FileService;  
  12.   
  13. public class ClickListener implements OnClickListener {  
  14.       
  15.     private FileService fileService;  
  16.     private EditText editText;  
  17.     private TextView show_text;  
  18.     private Context context;  
  19.   
  20.     public ClickListener(Context context) {  
  21.         this.context=context;  
  22.         fileService = new FileService(context);  
  23.         Activity activity = (Activity) context;  
  24.         editText = (EditText) activity.findViewById(R.id.edit_name);  
  25.         show_text = (TextView) activity.findViewById(R.id.show_text);  
  26.     }  
  27.   
  28.     @Override  
  29.     public void onClick(View v) {  
  30.         // TODO Auto-generated method stub  
  31.         switch (v.getId()) {  
  32.         case R.id.ok_button:  
  33.             String name=editText.getText().toString();  
  34.             try {  
  35.                 fileService.saveName(name);  
  36.                 Toast.makeText(context, R.string.ok_succee, Toast.LENGTH_SHORT).show();  
  37.             } catch (Exception e) {  
  38.                 // TODO Auto-generated catch block  
  39.                 e.printStackTrace();  
  40.                 //Toast.makeText(contex, R.string.ok_error, Toast.LENGTH_SHORT).show();  
  41.             }  
  42.             break;  
  43.   
  44.         case R.id.read_button:  
  45.             try {  
  46.                 String name1 =fileService.getName();  
  47.                 show_text.setText(name1);  
  48.             } catch (Exception e) {  
  49.                 // TODO Auto-generated catch block  
  50.                 e.printStackTrace();  
  51.                 Toast.makeText(context, R.string.read_error, Toast.LENGTH_SHORT).show();  
  52.             }  
  53.             break;  
  54.         }  
  55.     }  
  56.       
  57. }  

Activity 

[java] view plaincopy
  1. package demo.filerw;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.widget.Button;  
  6. import demo.filerw.clicklistener.ClickListener;  
  7.   
  8.   
  9. public class FileRWActivity extends Activity {  
  10.       
  11.     private Button ok_button;  
  12.     private Button read_button;  
  13.       
  14.       
  15.     /** Called when the activity is first created. */  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.           
  21.         ok_button = (Button) findViewById(R.id.ok_button);  
  22.         read_button = (Button) findViewById(R.id.read_button);  
  23.           
  24.         ok_button.setOnClickListener(new ClickListener(this));  
  25.         read_button.setOnClickListener(new ClickListener(this));  
  26.           
  27.     }  
  28.    
  29. }  

main.xml

[java] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.     <TextView  
  12.         android:layout_width="fill_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:text="@string/name_lable"   
  15.         />  
  16.     <EditText   
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:id="@+id/edit_name"  
  20.         />  
  21.     <LinearLayout   
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:orientation="horizontal" >  
  25.         <Button   
  26.             android:id="@+id/ok_button"  
  27.             android:layout_width="fill_parent"  
  28.             android:layout_height="fill_parent"  
  29.             android:text="@string/ok_button"  
  30.         />  
  31.          <Button   
  32.             android:id="@+id/read_button"  
  33.             android:layout_width="fill_parent"  
  34.             android:layout_height="fill_parent"  
  35.             android:text="@string/read_button"  
  36.         />  
  37.     </LinearLayout>  
  38.         <TextView  
  39.             android:id="@+id/show_text"  
  40.             android:layout_width="fill_parent"  
  41.             android:layout_height="wrap_content"  
  42.         />  
  43. </LinearLayout>  


使用 单元 测试  来测试 FileService 类 

配置 单元测试  和 配置 SDcard  所需要的权限

[java] view plaincopy
  1.    <uses-sdk android:minSdkVersion="10" />  
  2.    <!-- 在SDCard中创建与删除文件权限 -->  
  3. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
  4. <!-- 往SDCard写入数据权限 -->  
  5. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  6.      
  7. <instrumentation   
  8.     android:name="android.test.InstrumentationTestRunner"   
  9.     android:targetPackage="demo.filerw" android:label="ServiceTest"  
  10.     />  
  11.    <application  
  12.        android:icon="@drawable/ic_launcher"  
  13.        android:label="@string/app_name" >  
  14.        <uses-library android:name="android.test.runner" />  
  15.        <activity  
  16.            android:label="@string/app_name"  
  17.            android:name=".FileRWActivity" >  
  18.            <intent-filter >  
  19.                <action android:name="android.intent.action.MAIN" />  
  20.   
  21.                <category android:name="android.intent.category.LAUNCHER" />  
  22.            </intent-filter>  
  23.        </activity>  
  24.    </application>  

测试类 

[java] view plaincopy
  1. package demo.filerw;  
  2.   
  3. import demo.filerw.service.FileService;  
  4. import android.os.Environment;  
  5. import android.test.AndroidTestCase;  
  6. import android.util.Log;  
  7.   
  8. public class FileTest extends AndroidTestCase {  
  9.   
  10.     private static final String TAG="FileTest";  
  11.     //存储数据  
  12.     public void testSaveName() throws Exception{  
  13.         FileService fileService=new FileService(this.getContext());  
  14.         fileService.saveName("李明");  
  15.     }  
  16.       
  17.     public void testSaveNameToSDCard() throws Exception{  
  18.           
  19.         if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {  
  20.             FileService fileService = new FileService(this.getContext());  
  21.             fileService.saveNameToSDCard("李明和小强");  
  22.         } else {  
  23.             Log.e(TAG, "sdcard not exsit or only read");  
  24.         }  
  25.           
  26.           
  27.     }  
  28.       
  29.     public void getSaveName() throws Exception{  
  30.         FileService fileService=new FileService(this.getContext());  
  31.         String name=fileService.getName();  
  32.           
  33.         Log.i(TAG, name);  
  34.     }  
  35. }