首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

把数据写下到文件或者读取文件内容

2012-09-28 
把数据写入到文件或者读取文件内容首先写读取和写入的两个方法static public String ReadActivityFile(Con

把数据写入到文件或者读取文件内容

首先写读取和写入的两个方法
static public String ReadActivityFile(Context aContext, String aFile) {String buffer="";FileInputStream in2;try {in2 = aContext.openFileInput(aFile);InputStreamReader inReader = new InputStreamReader(in2);int buf= 1024;BufferedReader line = new BufferedReader(inReader,buf);String tmpBuffer = "";while ((tmpBuffer = line.readLine()) != null) {buffer += tmpBuffer;}line.close();inReader.close();in2.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return buffer;}static public void WriteActivityFile(Context aContext, String aFile,String aBuffer) {try {FileOutputStream os = aContext.openFileOutput(aFile,Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);OutputStreamWriter outWriter = new OutputStreamWriter(os);outWriter.write(aBuffer, 0, aBuffer.length());outWriter.flush();outWriter.close();os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

?然后在需要用的地方调用就行了,把需要的参数完成:

读取:

String buffer = "";buffer = FileUtils.ReadActivityFile(ScoreActivity.this,common.FAVORITE_DATA_FILE);

?写入:

FileUtils.WriteActivityFile(ScoreActivity.this,common.FAVORITE_DATA_FILE, buffer);

?

?

下面的一个例子是:点击一次,把这条数据保存到文件里面,然后再点击一次,又取消保存,就是从文件删除:

LinearLayout ly = (LinearLayout) layout.findViewById(R.id.linear_score_choise);ly.setOnClickListener(new OnClickListener() {public void onClick(View arg0) {String buffer = "";buffer = FileUtils.ReadActivityFile(ScoreActivity.this,common.FAVORITE_DATA_FILE);boolean isFileBlank = false;if (buffer.length() <= 0) {// 如果buffer为空,则为true;isFileBlank = true;}boolean has_fav = false;// 如果buffer不为空if (!isFileBlank) {// 解析到集合中Vector fav_list = CommonUtil.Split(buffer, ",");buffer = "";// buffer初始化for (int i = 0; i < fav_list.size(); i++) {String fav_id = (String) fav_list.elementAt(i);// System.out.println(fav_id);if (fav_id.equals(mId)) {has_fav = true;continue;}if (fav_id.length() <= 0) {continue;}buffer += fav_id;if (i != fav_list.size() - 1) {buffer += ",";}}}if (buffer.length() > 0&& buffer.charAt(buffer.length() - 1) == ',') {buffer = buffer.substring(0, buffer.length() - 1);}if (has_fav) {// 取消关注imageView.setImageResource(R.drawable.gray_star);Toast.makeText(ScoreActivity.this, "该场关注已取消!",Toast.LENGTH_SHORT).show();FileUtils.WriteActivityFile(ScoreActivity.this,common.FAVORITE_DATA_FILE, buffer);} else {// 关注if (!isFileBlank) {// 如果buffer有数据buffer += ",";}buffer += mId;imageView.setImageResource(R.drawable.yellow_star);Toast.makeText(ScoreActivity.this, "该场比赛已成功关注!",Toast.LENGTH_SHORT).show();FileUtils.WriteActivityFile(ScoreActivity.this,common.FAVORITE_DATA_FILE, buffer);}}});

?

热点排行