首先写读取和写入的两个方法
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); } } });