Android: Write text to txt

user896692 picture user896692 · Jun 7, 2013 · Viewed 16.7k times · Source

With the following code, I try to write to my sdcard:

public void writedata(String data) {
          //BufferedWriter out = null;

          System.out.println(data);
          try{

              FileOutputStream out = new FileOutputStream(new File("/sdcard/tsxt.txt"));
              out.write(data.getBytes());
              out.close();  

                } catch (Exception e) { //fehlende Permission oder sd an pc gemountet}
                    System.out.println("CCCCCCCCCCCCCCCCCCCCCCCALSKDJLAK");
                }

          }

The permission in the Manifest:

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

But now, when I open the file, nothing is in there. Where´s the problem? I´m sure data has some value.

EDIT:

I get this message in the LogCat:

02-06 01:59:51.676: W/System.err(1197): java.io.FileNotFoundException: /storage/sdcard0/sdcard/tsxt.txt: open failed: ENOENT (No such file or directory)

I tried to create the file on the sdcard but still the same error. Is there a code that the File is created if it doesn´t exists?

Answer

mez picture mez · Jun 7, 2013

Try with this code:

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir");

File file = new File(dir, "tsxt.txt");

FileOutputStream f = new FileOutputStream(file);

So the path to the file is not correct. You should remove directory name:

File dir = new File (sdCard.getAbsolutePath() + "/");