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

本文介绍了Android应用中使用Content的openFileOutput和openFileInput操作文件的基本方法,包括存储数据到文件、存储数据到SD卡、从文件读取数据等,并通过单元测试验证了这些操作的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

事件监听类可以放到外边

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

Activity

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

main.xml

  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.     <TextView
  7.         android:layout_width=”fill_parent”
  8.         android:layout_height=”wrap_content”
  9.         android:text=”@string/hello” />
  10.     <TextView
  11.         android:layout_width=”fill_parent”
  12.         android:layout_height=”wrap_content”
  13.         android:text=”@string/name_lable”
  14.         />
  15.     <EditText
  16.         android:layout_width=”fill_parent”
  17.         android:layout_height=”wrap_content”
  18.         android:id=”@+id/edit_name”
  19.         />
  20.     <LinearLayout
  21.         android:layout_width=”wrap_content”
  22.         android:layout_height=”wrap_content”
  23.         android:orientation=”horizontal” >
  24.         <Button
  25.             android:id=”@+id/ok_button”
  26.             android:layout_width=”fill_parent”
  27.             android:layout_height=”fill_parent”
  28.             android:text=”@string/ok_button”
  29.         />
  30.          <Button
  31.             android:id=”@+id/read_button”
  32.             android:layout_width=”fill_parent”
  33.             android:layout_height=”fill_parent”
  34.             android:text=”@string/read_button”
  35.         />
  36.     </LinearLayout>
  37.         <TextView
  38.             android:id=”@+id/show_text”
  39.             android:layout_width=”fill_parent”
  40.             android:layout_height=”wrap_content”
  41.         />
  42. </LinearLayout>

 

使用 单元 测试  来测试 FileService 类

 

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

  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. <instrumentation
  7.     android:name=”android.test.InstrumentationTestRunner”
  8.     android:targetPackage=”demo.filerw” android:label=”ServiceTest”
  9.     />
  10.    <application
  11.        android:icon=”@drawable/ic_launcher”
  12.        android:label=”@string/app_name” >
  13.        <uses-library android:name=”android.test.runner” />
  14.        <activity
  15.            android:label=”@string/app_name”
  16.            android:name=”.FileRWActivity” >
  17.            <intent-filter >
  18.                <action android:name=”android.intent.action.MAIN” />
  19.                <category android:name=”android.intent.category.LAUNCHER” />
  20.            </intent-filter>
  21.        </activity>
  22.    </application>

测试类

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值