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

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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值