Kripzy
Kripzy

Reputation: 39

How to read and write text to a file

I want to code a program which gets 3 textbox values and 1 global variable saved in a text document, however i want to append to the text document, instead of rewriting it each time! This is what i have so far;

public class Proceed extends Activity {

    // Defining edittext variables and where they will be used
    EditText edittext;
    EditText edittext1;
    EditText edittext2;

    // Getting global variable to get price data from past activity
    String PriceResult = Main2Activity.GSTFinal;

    // Defining textview to show data
    TextView tvResult2;

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

        // assigning variables from their respective EditText and textview box
        edittext = (EditText) findViewById(R.id.Name);
        edittext1 = (EditText) findViewById(R.id.Phone);
        edittext2 = (EditText) findViewById(R.id.Address);
        tvResult2 = (TextView) findViewById(R.id.tvResult2);
        // Assigning tvresult what string to show
        tvResult2.setText(PriceResult + "");
        //
    }

    public void save(View view) {
        String n1 = edittext.getText().toString();
        String n2 = edittext1.getText().toString();
        String n3 = edittext2.getText().toString();
        String n4 = tvResult2.getText().toString();
        String Writetotxtfile = n1 + "," + n2 + "," + n3 + "," + n4;
        String filename = "myfile";
        FileOutputStream outputStream;

        try {
            outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
            outputStream.write(Writetotxtfile.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Upvotes: 0

Views: 109

Answers (3)

Parag Chauhan
Parag Chauhan

Reputation: 35946

For Read file

public String readFromFile() {
            File sdcard = Environment.getExternalStorageDirectory();
            File file = new File(sdcard,".YOURAPP/myFile.txt");
            StringBuilder text = new StringBuilder();
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                }
                br.close();
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }
            return text.toString();
        }

For Write file

 public void writeFile(String data){
        try {
            File logFile = new File(Environment.getExternalStorageDirectory().toString(), ".YOURAPP/myFile.txt");
            File dirFile = new File(Environment.getExternalStorageDirectory().toString(), ".YOURAPP");
            if(!logFile.exists()) {
                dirFile.mkdir();
                logFile.createNewFile();
            }
            BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
            output.write(data);
            output.close();
        }catch (Exception e){
            System.out.print("Exception e"+e);
        }
    }

For Delete file

 public void deleteFile(){

        File logFile = new File(Environment.getExternalStorageDirectory().toString(), ".YOURAPP/myFile.txt");
        File dirFile = new File(Environment.getExternalStorageDirectory().toString(), ".YOURAPP");
        if(logFile.exists()) {
            logFile.delete();
            dirFile.delete();

        }
    }

Add permission to menifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Upvotes: 1

giannisf
giannisf

Reputation: 2599

What you are trying to do is called

append

FileOutputStream has a Constructor for appending.

Creates a file output stream to write to the file represented by the specified File object.

FileOutputStream(File file, boolean append)

So use that constructor when instantiating your FileOutputStream.

Upvotes: 0

Top Sekret
Top Sekret

Reputation: 758

Instead of

outputStream = openFileOutput(filename, Context.MODE_PRIVATE);

use

outputStream = new FileOutputStream(filename, true);

This will ensure you append to file, not truncate it.

Upvotes: 0

Related Questions