- Forum posts: 2
Mar 25, 2016, 7:44:10 AM via Website
Mar 25, 2016 7:44:10 AM via Website
I am trying to write lines of string in to a text file, but I do not know why all the lines are duplicated. I tried to use a code to delete the string but apparently it is not working as well.
Below are my codes that write to the text file, and the code I use to delete the duplicated lines.
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("Object " + (score+1) + " took " + saveText + "seconds");
out.newLine();
out.newLine();
out.close();
} catch (Throwable t){
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
}
I call saveText upon clicking on the image
imgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopTimer();
saveText();
resetTimer();
imgView.setImageDrawable(null);
score++;
counterTouch++;
tempScore = String.valueOf(score);
textViewScore.setText(tempScore);
drawCircle();
}
});
}
This is the code that I use to read from the text file.
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 = "";
String tempString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
if ((receiveString.equals(tempString)) == false){
tempString = receiveString;
stringBuilder.append(receiveString);
stringBuilder.append('\n');
}
else
{
}
}
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);
}
Hope someone can advice me on this.
Recommended editorial content
With your consent, external content is loaded here.
By clicking on the button above, you agree that external content may be displayed to you. Personal data may be transmitted to third-party providers in the process. You can find more information about this in our Privacy Policy.