Search code examples
androidwritetofile

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.


Solution

  • 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" />