Ingrid Stoleru
Ingrid Stoleru

Reputation: 43

Android write to file not working

I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me? The code looks like that:

submit.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
          StringBuilder s = new StringBuilder();
          s.append("Event name: " + editText1.getText() + "|");
          s.append("Date: " + editText2.getText() +  "|");
          s.append("Details: " + editText3.getText() + "|");

          File file = new File("D:\\config.txt");
          try {
              BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
                out.write(s.toString());
                out.newLine();
                out.close();
           } catch (IOException e) {
                e.printStackTrace();
           }
      }
});

So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.

Upvotes: 2

Views: 4140

Answers (2)

PEHLAJ
PEHLAJ

Reputation: 10126

Use following path for file. It will write file to your root folder of storage.

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");

writeToFile("File content".getBytes(), file);

writeToFile

public static void writeToFile(byte[] data, File file) throws IOException {

    BufferedOutputStream bos = null;

    try {
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data);
    }
    finally {
        if (bos != null) {
            try {
                bos.flush ();
                bos.close ();
            }
            catch (Exception e) {
            }
        }
    }
}

Don't forget to add following permission in AndroidManifest.xml

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

Upvotes: 2

rznazn
rznazn

Reputation: 41

https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java

Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.

Don't forget to add the write permissions to manifest.

Upvotes: -1

Related Questions