`

android读写文件操作

阅读更多
package com.example.service;

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 android.content.Context;
import android.os.Environment;



public class FileService {
	private Context context;
	public FileService(Context context){
		this.context=context;
	}
	/**
	 * 保存文件
	 * @param name
	 * @param content
	 * @throws FileNotFoundException 
	 */
	public void save(String name,String content) throws Exception{
		//私有操作模式:创建出来的文件仅能被本应用访问,其它应用无法访问该文件。
		//另会覆盖原文件的内容
		FileOutputStream o=context.openFileOutput(name, Context.MODE_PRIVATE);
		write(content, o);
	}
	
	/**
	 * 写入
	 * @param content
	 * @param o
	 * @throws IOException
	 */
	private void write(String content, FileOutputStream o) throws IOException {
		o.write(content.getBytes());
		o.close();
	}
	
	/**
	 * 追加文件
	 * @param filename
	 * @param content
	 * @throws Exception
	 */
	public void saveAppend(String filename,String content)throws Exception{
		FileOutputStream o=context.openFileOutput(filename, Context.MODE_APPEND);//保存在手机自带的文件里面
		write(content, o);
	}
	
	/**
	 * 文件,当前文件可以被其他应用读取
	 * @param filename
	 * @param content
	 * @throws Exception
	 */
	public void saveReadable(String filename,String content)throws Exception{
		FileOutputStream o=context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
		write(content, o);
	}
	
	/**
	 * 保存文件到SD卡上.需要申请往SD卡写入数据的权限
	 * @param filename
	 * @param content
	 * @throws Exception
	 */
	public void saveToSDCard(String filename,String content)throws Exception{
		File file=new File(Environment.getExternalStorageDirectory(),filename);
		FileOutputStream o=new FileOutputStream(file);
		o.write(content.getBytes());
		o.close();
	}
	
	/**
	 * 当前文件可以被其他应用写入
	 * @param filename
	 * @param content
	 * @throws Exception
	 */
	public void saveWriteable(String filename,String content)throws Exception{
		FileOutputStream o=context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
		write(content, o);
	}
	/**
	 * 读取文件
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public String read(String filename)throws Exception{
		FileInputStream i=context.openFileInput(filename);
		ByteArrayOutputStream bs=new ByteArrayOutputStream();
		byte[] buffer=new byte[1024];
		int len=0;
		//-1表示读到文件的末尾
		while((len=i.read(buffer))!=-1){
			bs.write(buffer,0,len);
		}
		byte[] data=bs.toByteArray();
		return new String(data);
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics