Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Write text to txt

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?

like image 403
user896692 Avatar asked Feb 17 '23 07:02

user896692


1 Answers

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() + "/");
like image 142
mez Avatar answered Feb 28 '23 07:02

mez