文件操作

import java.io.*;

import android.content.Context;
import android.os.Environment;

public class SaveFile
{
//获取上下文变量
private Context context;

public SaveFile(Context context) 
{
super();
this.context = context;
}
/**
* @param name
* @param content
* @throws IOException
*/
public void save(String name,String content) throws IOException
{

FileOutputStream stream=context.openFileOutput(name, Context.MODE_PRIVATE);
stream.write(content.getBytes());
stream.close();
}

public void savetoSdcard(String name,String content) throws IOException
{
File file=new File(Environment.getExternalStorageDirectory(),name);

FileOutputStream stream=new FileOutputStream(file);
stream.write(content.getBytes());
stream.close();
}

//读文件
public String readFile(String name) throws Exception
{
FileInputStream instr=context.openFileInput(name);
byte[] buffer=new byte[1024];
int innum=0;
ByteArrayOutputStream outstr=new ByteArrayOutputStream();
while((innum=instr.read(buffer))!=-1)
{
outstr.write(buffer, 0, innum);
}
byte[] endout=outstr.toByteArray();
outstr.close();
instr.close();
return new String(endout);
}

}添加权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

posted @ 2011-12-08 16:05  乌托邦.  阅读(123)  评论(0编辑  收藏  举报