How do I write to a .txt file in Android?
Asked Answered
M

2

14

I have an app that needs to read and write to a text file. I have it reading, but I don't have it writing. The idea is that when I click the save button on the screen, its going to save all the info that has been put into the textviews into an array and the write each segment of the array into the text file. This is my code for the writing portion:

public class AddOrModify extends Activity {

    private Button Savebtn;
    private Button Cancelbtn;
    private EditText NameofRoute;
    private EditText Address1;
    private EditText City1;
    private EditText State1;
    private EditText Zip1;
    private EditText Address2;
    private EditText City2;
    private EditText State2;
    private EditText zip2;




        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_or_modify);

            Savebtn = (Button)findViewById(R.id.savebtn);
            Savebtn.setOnClickListener(new btnlistenersave());

            Cancelbtn = (Button)findViewById(R.id.cancelbtn);
            Cancelbtn.setOnClickListener(new btnlistenercancel());

        }

        private class btnlistenersave implements View.OnClickListener{
            public void onClick(View v) {

                NameofRoute = (EditText)findViewById(R.id.NameofRoute);
                Address1 = (EditText)findViewById(R.id.editAddress1);
                City1 = (EditText)findViewById(R.id.City1);
                State1= (EditText)findViewById(R.id.State1);
                Zip1 = (EditText)findViewById(R.id.Zip1);
                Address2= (EditText)findViewById(R.id.Address2);
                City2 = (EditText)findViewById(R.id.City2);
                State2 = (EditText)findViewById(R.id.State2);
                zip2 = (EditText)findViewById(R.id.Zip2);

                //String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};


               // if(mySettings != null){ 
                try{

                    String NameofRouteinput = NameofRoute.getText().toString();
                    String Address1input = Address1.getText().toString();
                    String City1input = City1.getText().toString();
                    String State1input=State1.getText().toString();
                    String Zip1input = Zip1.getText().toString();
                    String Address2input =Address2.getText().toString();
                    String City2input = City2.getText().toString();
                    String State2input = State2.getText().toString();
                    String Zip2input= zip2.getText().toString();
                    OutputStreamWriter out = new OutputStreamWriter(openFileOutput("myaddress.txt",0));

                    String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};


                    for(int i =0; i < mySettings.length; i++)
                    out.write(mySettings[i]);
                    out.close();
                }
                catch (java.io.IOException e){

                }


                Intent i = new Intent(AddOrModify.this, Frontpage.class);
                startActivity(i);

            }

        }

        private class btnlistenercancel implements View.OnClickListener{

            public void onClick(View v) {
                Intent i = new Intent(AddOrModify.this, Frontpage.class);
                startActivity(i);
            }

        }

}
Manned answered 8/12, 2012 at 16:13 Comment(0)
R
17

with mari's solution i was getting

       java.lang.IllegalArgumentException: contains a path separator

then i tried following and it worked for me

  File root = new File(DIRECTORY_PATH);
  File gpxfile = new File(root, "samples.txt");
  FileWriter writer = new FileWriter(gpxfile);
  writer.append("First string is here to be written.");
  writer.flush();
  writer.close();

you can loop it to write multiple lines

Resort answered 7/1, 2015 at 9:19 Comment(3)
What is DIRECTORY_PATH equal to?Antirachitic
@Antirachitic You can either use default directory Environment.getExternalStorageDirectory().toString() or if you have created your own Directory then you use some thing like Environment.getExternalStorageDirectory().toString()+"/Your Directory/"Resort
Ahh understood :) I would prefer File path = new File(Environment.getExternalStorageDirectory(),"Your Directory/subpath/a" ) this will look after the / . but thanks for teaching me about Environment - new to android developer.android.com/reference/android/os/Environment.htmlAntirachitic
N
6

You can use FileOutputStream instead of OutputStreamWriter, something like this:

File file = getFileStreamPath("test.txt");

if (!file.exists()) {
   file.createNewFile();
}

FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);

for (String string: data){
    writer.write(string.getBytes());
    writer.flush();
}

writer.close();

Check the android docs.

Nomadic answered 8/12, 2012 at 16:29 Comment(4)
Can i do this with a whole array though? your example has me writing one string, i need to do that for many values, or am i going to have to do them individually?Manned
Yes, should work too... i updated the answer for you. I hope I helped.Nomadic
What is supposed to go in the "data" area? I've tried putting a string, a string array, and a bunch of other things there. Either it gives me an error, or makes all of the other lines get an IOException.Pero
@Dooomsknight That's what I thought too. But I get an IOException on every other line when I do that. What wound up happening is that I needed to surround it in a try/catch.Pero

© 2022 - 2024 — McMap. All rights reserved.