ファイルにデータを書き込むか、ファイルの内容を読み取る
4077 ワード
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);
}
}
});