Coda759
Coda759

Reputation: 107

Appending to text file in android

I am trying to append to a text file that starts off empty and every time the method addStudent() is called it would add a student.toString() line to the said file. I don't seem to get any exceptions but for some reason, after the method call, the file remains empty. Here is my code.

public void addStudent() {
        Student student = new Student();
        EditText fName = findViewById(R.id.first_name);
        EditText lName = findViewById(R.id.last_name);
        EditText studentGpa = findViewById(R.id.gpa);
        String firstName = String.valueOf(fName.getText());
        String lastName = String.valueOf(lName.getText());
        String gpa = String.valueOf(studentGpa.getText());

        if(firstName.matches("") || lastName.matches("") || gpa.matches("")) {
            Toast.makeText(this, "Please make sure none of the fields are empty", Toast.LENGTH_SHORT).show();
        } else {
            double gpaValue = Double.parseDouble(gpa);
            student.setFirstName(firstName);
            student.setLastName(lastName);
            student.setGpa(gpaValue);
            try {
                FileOutputStream fos = openFileOutput("students.txt",  MODE_APPEND);
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                osw.write(student.toString());
                osw.flush();
                osw.close();
            } catch(FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

What might be the problem here? The file students.txt itself is located in assets folder

Upvotes: 0

Views: 78

Answers (2)

blackapps
blackapps

Reputation: 9282

What might be the problem here? The file students.txt itself is located in assets folder.

If it is in the assets folder then you should use AssetsManager top open an input stream to it. Files in the assets folder are readonly so trying to write to them does not make sense.

FileOutputStream fos = openFileOutput("students.txt",  MODE_APPEND);

That wil create a file in private internal memory of your app. The code looks ok. But it makes no sense trying to find the file on your phone with a file manager or other app as as said that is private internal memory of your app only.

You use a relative path with "studends.txt" and now you do not know where the file resides.

Well the file resides in the path indicated by getFilesDir().

You could as well have used a full path with

 File file = new File(getFilesDir(), "students.txt");

and then open a FileOutputStream with

FileOutputStream fos = new FileOutputStream(file);

Upvotes: 1

Gralls
Gralls

Reputation: 156

The problem may be with the fact that 'assets' directory doesnt exists on phone. So if I understand you correctly you may checking the wrong file.

Upvotes: 2

Related Questions