我的应用程序假设记录单击图像所花费的时间。因此,字符串被写入文件。每次用户单击图像时,都会调用savetext函数。但我的输出总是有一个字符串的副本?任何人都可以就此提出建议吗?
public void saveText(){
int seconds;
String saveText;
long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase();
seconds = (int) (elapsedMillis / 1000);
saveText = String.valueOf(seconds);
try {
FileOutputStream writer = openFileOutput("logs.txt", MODE_APPEND);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(writer));
out.write(saveText);
out.newLine();
out.close();
} catch (Throwable t){
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
}
这是我调用保存文字的地方:
public void drawCircle() {
mChronometer = new Chronometer(this);
final LinearLayout button_container = (LinearLayout) findViewById(R.id.my_window);
final ImageButton imgView = (ImageButton)findViewById(R.id.gameass);
imgView.setImageResource(R.drawable.gameass);
imgView.setVisibility(View.VISIBLE);
int x = (int) (Math.random() * (button_container.getWidth() - imgView.getWidth()));
int y = (int) (Math.random() * (button_container.getHeight() - imgView.getHeight()));
button_container.setPadding(x, y, 0, 0);
startTimer();
imgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveText();
stopTimer();
resetTimer();
imgView.setImageDrawable(null);
score++;
counterTouch++;
tempScore = String.valueOf(score);
textViewScore.setText(tempScore);
drawCircle();
}
});
}
我使用其他活动查看日志。
private void readfromFile() {
StringBuilder stringBuilder = new StringBuilder();
try {
InputStream inputStream = openFileInput("logs.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
stringBuilder.append('\n');
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
TextView output=(TextView) findViewById(R.id.logs);
output.setText(stringBuilder);
}