android01

【文件读取】

public class Fileservice {

private Context context; //android 提供的上下文对象

 

public Fileservice(Context context) {

super();

this.context = context;

}

 

/**

 * 文件存储

 * @param fileName

 * @param fileContent

 */

public void savefile(String fileName, //文件名称

 String fileContent //文件内容

throws Exception{

// 【上下文对象context提供的openFileOutput方法,可以快速的获取文件输出流对象】

FileOutputStream outStr = context.openFileOutput(fileName, Context.MODE_PRIVATE);

outStr.write(fileContent.getBytes()); //write(byte[] buffer)

outStr.close();

}

/**

 * 文件读取

 * @param fileName

 * @return

 * @throws Exception

 */

public String read(String fileName) throws Exception

{

FileInputStream inStr = context.openFileInput(fileName);

ByteArrayOutputStream outStr = new ByteArrayOutputStream(); //字节数组流对象

byte[] buffer = new byte[1024];   //建字节数组

 

int len = 0;

while ( ( len = inStr.read(buffer) ) != -1 ) //从指定文件中读取流到buffer中,直到读完

{

outStr.write(buffer, 0, len); //先保存到内存,再一次性读入

}

byte[] data = outStr.toByteArray();  //得到内存字节数据

 

String dataString = new String(data);

return dataString;

}

 

}

//----------------------------

使用:

Fileservice fileSvr = new Fileservice(getApplicationContext());

try {

fileSvr.savefile(fileName, fileContent);

Toast.makeText(getApplicationContext(), R.string.success, 1).show(); //提示成功

catch (Exception e) {

// TODO: handle exception

Toast.makeText(getApplicationContext(), R.string.fail, 1).show(); //提示失败

e.printStackTrace();

}

 

PS : Java中使用 public xxx类创建对象时,会在文件顶部自动添加相应的包,C++需要手动添加相应的.h文件。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2013-05-22 01:04  海之涯2008  阅读(165)  评论(0)    收藏  举报