Duplicated string in text file

  • Replies:1
  • OpenNot stickiedUnanswered
  • Forum posts: 2

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. image

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.

  • Forum posts: 12

Mar 25, 2016 1:42:34 PM via Website

The source code provided appears to work as expected - the following reproduction produces the expected results:

public class MainActivity extends AppCompatActivity {
    private int score = 0;

    public void saveText(){
        int seconds;
        String saveText;
        long elapsedMillis = 0; //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();
        }
    }

    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);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final File file = new File(getFilesDir(), "logs.txt");
        if (file.exists())
            file.delete();

        final ImageView imgView = (ImageView)findViewById(R.id.add);
        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();
            }
        });

        findViewById(R.id.display).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readfromFile();
                imgView.setImageDrawable(getTheme().getDrawable(android.R.drawable.ic_input_add));
            }
        });
    }
}

image

The conditional you tried to use to filter out duplicate lines fails because you emit a second newline in saveText; readfromFile will read "Object 1 ...", "", "Object 1 ...", "", "Object 2 ...", and so on. The following change would likely suffice:

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.isEmpty()) {
                    stringBuilder.append('\n');
                } else 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);
}

— modified on Mar 25, 2016 1:43:37 PM