手机内存、sdcard读写操作学习笔记

来源:互联网 发布:vmware linux nat模式 编辑:程序博客网 时间:2024/06/06 01:32
package com.lzj.saveAndRead;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.ContentHandler;import org.apache.http.util.ByteArrayBuffer;import android.content.Context;import android.graphics.Path;import android.os.Environment;public class FileManage {private Context context;public FileManage(Context context){this.context=context;}/** * 手机内存读写 * @param title 文件名 * @param body 内容 *  */public void writeToPhone(String title,String body) throws Exception{FileOutputStream fos = context.openFileOutput(title, Context.MODE_APPEND);fos.write(body.getBytes());fos.close();}public String readFromPhone(String title1) throws Exception {// TODO Auto-generated method stubFileInputStream fis = context.openFileInput(title1);BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(fis));String data = bufferedReader.readLine();fis.close();return data;}/** * sdcard读写操作 * @param title3 文件名 * @param body3 内容 * @throws Exception */public void writeToSdcard(String title3, String body3) throws Exception {// TODO Auto-generated method stubif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){File toolPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);File file=new File(toolPath,title3);FileOutputStream fos=new FileOutputStream(file);fos.write(body3.getBytes());fos.close();}}public String readFromSdcard(String title4) throws Exception {// TODO Auto-generated method stub//File filesDir = context.getExternalFilesDir(Environment.MEDIA_MOUNTED);if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){File rootPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);File file=new File(rootPath,title4);FileInputStream fs=new FileInputStream(file);//缓存ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=-1;while ((len=fs.read(buffer))!=-1) {baos.write(buffer,0,len);}baos.close();fs.close();return new String(baos.toByteArray());}return null;}}

0 0
原创粉丝点击