Content的openFileOutput 和 openFileInput操作文件
以下是自己写的基于MVC的文件保存:
Model 模型------业务逻辑层(APP中的二进制的数据)
View 视图------与用户交互(Android中通常将其保存在XML如:main.XML)
Controller 控制-----是确保M和V的同步和沟通(Activity 桥梁)
先来M层:
1 package filepackage.Service; 2 import java.io.ByteArrayOutputStream; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import android.R.integer; 6 import android.R.string; 7 import android.content.Context; 8 9 public class FileService { 10 11 private Context context;//context也可以改aaa 12 13 public FileService(Context context)//构造函数 14 { 15 //super(); 16 this.context = context; 17 } 18 public void Save(String filename,String content) throws Exception{ 19 FileOutputStream outStream= context.openFileOutput(filename,context.MODE_PRIVATE); 20 //(要保存的文件名称不能是路径,操作模式有4种本代码用的是私有模式,只能应用本身访问) 21 outStream.write(content.getBytes());//文件流提供了一个write的方法(也就是保存, 写入)不过要把传进的文件转成二进制 22 outStream.close();//文件保存好了,要把文件流关闭 23 } 24 public String opens(String filename) throws Exception//传一个参数“文件名” 25 { 26 FileInputStream inputStream=context.openFileInput(filename);//读取文件时只需要指定文件名就可以了。 27 byte[ ] buffer =new byte[1024];//建一个buffer的数组1024字节(1K),做缓冲区。 28 int len =0;//存放字节长度 29 ByteArrayOutputStream outStream=new ByteArrayOutputStream();//创建一个内存空间,为了下面read每次读取的数据流累加存放。 30 while ((len=inputStream.read(buffer)) !=-1)//返回读取的字节长度,如果读取到了末尾放回-1, 31 { 32 outStream.write(buffer, 0, len);//把缓冲区里的数据写入内存,括号里的解释(缓冲区数据,开始读取位置,数据长度) 33 } 34 byte[] data=outStream.toByteArray();//从内存中得到二进制数据。 35 outStream.close();//关闭内存输出流 36 inputStream.close();//关闭文件输入流 37 String result=new String(data);//通过String的构造器,实例后把二进制文件转成String类型 38 return result;//返回读取到的 39 } 40 }
C层:
1 package filepackage.namespace; 2 import javax.xml.transform.Result; 3 import filepackage.Service.FileService; 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.util.Log; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.EditText; 10 import android.widget.Toast; 11 12 public class FileActivity extends Activity { 13 /** Called when the activity is first created. */ 14 private static final String TAG="FileActivity";//定义一个“标志”的名字 15 private FileService fileservice;//定义属于业务层的一个全局的变量 16 public EditText text1;// 全局定义文本一边使用 17 public EditText text2; 18 @Override 19 public void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.main); 22 fileservice =new FileService(this);//从业务层(FileServic类)实例化一个fileservice 23 Button buttonsave = (Button)this.findViewById(R.id.buttonsave);//获取button1 24 Button buttonclear = (Button)this.findViewById(R.id.buttonclear); 25 Button buttonopen = (Button)this.findViewById(R.id.buttonopen); 26 text1=(EditText) findViewById(R.id.editText1);//获取文本1的内容filename 27 text2=(EditText)findViewById(R.id.editText2); 28 29 buttonsave.setOnClickListener(new View.OnClickListener()//保存 30 { 31 @Override 32 public void onClick(View v) { 33 String filename=text1.getText().toString(); 34 String content=text2.getText().toString(); 35 try { 36 fileservice.Save(filename, content);//调用业务类的save方法 37 Toast.makeText(FileActivity.this, R.string.success, 1).show(); 38 } catch (Exception e) { 39 Log.e(TAG, e.toString());//接收异常在控制台打印, 40 Toast.makeText(FileActivity.this, R.string.error, 1).show();//括号里的解释(context,提示内容,显示时间) 41 } 42 } 43 }); 44 buttonclear.setOnClickListener(new View.OnClickListener()//清除文本 45 { 46 @Override 47 public void onClick(View v) { 48 // TODO Auto-generated method stub 49 text1.setText(""); 50 text2.setText(""); 51 } 52 }); 53 buttonopen.setOnClickListener(new View.OnClickListener()//用fileinputstream读取 54 { 55 @Override 56 public void onClick(View v) { 57 // TODO Auto-generated method stub 58 String openfilename=text1.getText().toString(); 59 try { 60 fileservice.opens(openfilename); 61 Toast.makeText(FileActivity.this, R.string.success, 1).show(); 62 } catch (Exception e) { 63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 Toast.makeText(FileActivity.this, R.string.error, 1).show(); 66 } 67 } 68 }); 69 } 70 }
下面是我从其他网搜索来的:
- packagedemo.filerw.service;
- importjava.io.ByteArrayOutputStream;
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.FileOutputStream;
- importandroid.content.Context;
- importandroid.os.Environment;
- publicclassFileService{
- privateContextcontext;
- publicFileService(Contextcontext){
- this.context=context;
- }
- //存储数据到文件
- public void saveName(Stringname)throwsException{
- //context.getFilesDir();//得到存放文件的系统目录/data/data//files
- //context.getCacheDir();//缓存目录/data/data//cache
- FileOutputStream outputStream=context.openFileOutput(“deomfilerw.txt”, Context.MODE_APPEND);
- outputStream.write(name.getBytes());
- outputStream.close();
- }
- //存储数据到sdcard
- public void saveNameToSDCard(Stringname)throwsException{
- Environment.getExternalStorageDirectory(); //得到sdcard目录
- File file=new File(“/sdcard”,”demosdcard.txt”);
- FileOutputStreamoutputStream=newFileOutputStream(file);
- outputStream.write(name.getBytes());
- outputStream.close();
- }
- //读取数据
- public String getName()throwsException{
- FileInputStream inputStream=context.openFileInput(“deomfilerw.txt”);
- ByteArrayOutputStream outStream=new ByteArrayOutputStream();
- byte[] buffer=new byte[1024];
- int len=0;
- while ((len=inputStream.read(buffer))!=-1){
- outStream.write(buffer, 0, len);
- }
- outStream.close();
- byte[] data=outStream.toByteArray();
- String name=new String(data);
- returnname;
- }
- }
事件监听类可以放到外边
- packagedemo.filerw.clicklistener;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.EditText;
- importandroid.widget.TextView;
- importandroid.widget.Toast;
- importdemo.filerw.R;
- importdemo.filerw.service.FileService;
- publicclassClickListenerimplementsOnClickListener{
- private FileService fileService;
- private EditText editText;
- private TextView show_text;
- private Context context;
- public ClickListener (Contextcontext) {
- this.context=context;
- fileService=new FileService(context);
- Activityactivity=(Activity)context;
- editText=(EditText)activity.findViewById(R.id.edit_name);
- show_text=(TextView)activity.findViewById(R.id.show_text);
- }
- @Override
- public void onClick(Viewv){
- //TODOAuto-generatedmethodstub
- switch(v.getId()){
- caseR.id.ok_button:
- Stringname=editText.getText().toString();
- try{
- fileService.saveName(name);
- Toast.makeText(context,R.string.ok_succee,Toast.LENGTH_SHORT).show();
- }catch(Exceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- //Toast.makeText(contex,R.string.ok_error,Toast.LENGTH_SHORT).show();
- }
- break;
- caseR.id.read_button:
- try{
- Stringname1=fileService.getName();
- show_text.setText(name1);
- }catch(Exceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- Toast.makeText(context,R.string.read_error,Toast.LENGTH_SHORT).show();
- }
- break;
- }
- }
- }
Activity
- packagedemo.filerw;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.widget.Button;
- importdemo.filerw.clicklistener.ClickListener;
- publicclassFileRWActivityextendsActivity{
- privateButtonok_button;
- privateButtonread_button;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ok_button=(Button)findViewById(R.id.ok_button);
- read_button=(Button)findViewById(R.id.read_button);
- ok_button.setOnClickListener(newClickListener(this));
- read_button.setOnClickListener(newClickListener(this));
- }
- }