您的位置:首页 > 其它

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

2016-04-07 12:32 393 查看
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 stub
FileInputStream 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 stub
if(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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: