user1468102
user1468102

Reputation: 391

Save a file to the SD-card

.txt file need save in SD-card.

Save("n" + String.valueOf(key) + ".txt");

 private void Save(String FileName){
         File fileName = null;
         String sdState = android.os.Environment.getExternalStorageState();

         if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
             File sdDir = android.os.Environment.getExternalStorageDirectory();
             fileName = new File(sdDir, "FlyNote/"+FileName);
             } else {
                 fileName = context.getCacheDir();
             }
         if (!fileName.exists())
             fileName.mkdirs();
         try {
             FileWriter f = new FileWriter(fileName);
             f.write(editText2.getText().toString());
             f.flush();
             f.close();
         } catch (Exception e) {

         }
     }

But in the SD-card file saves as a folder. Folder "n5.txt" and other...

Upvotes: 1

Views: 1509

Answers (4)

Vivekanand
Vivekanand

Reputation: 755

Most of the methods given here is good... You could also use this following code:

    public static void addToFile(String file,String message){

    try {
        FileOutputStream fos = new FileOutputStream(file,true);
        fos.write(("\n"+message).getBytes());
        fos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Here "File" is a string which contains the path to your file eg: File = "/sdcard/parentPath/FileName.txt" and "message" is for obvious the message that you want to enter into the file. (considering the file contains txt contents)

Upvotes: 0

Anurag Ramdasan
Anurag Ramdasan

Reputation: 4340

When you test for exists, you are searching if Flynote/Filename exists or not and if it doesnt exist you create one using mkdirs.

fileName.mkdirs() makes a directory with the name of that file. Hence you find the error. Your mkdirs should only be for Flynote and not Flynote/+FileName

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

Try this,

If you are aiming for a file, why r u using "mkdir" that makes a directory not a file.

This code is to create a file:

File f = new File("/sdcard/n5.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferdWriter(fw);
bw.write("Hello");

To check if the Folder exist...

File f = new File("/sdcard/myfolder");
if (f.exists()){

   // do what u want

   }
else{
       // doesnt exists
      }

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

use

File  dir= new File(sdDir.getAbsolutePath(), "FlyNote");
dir.mkdirs(); //CREATE DIR HERE
File  file = new File(dir, FileName);//CREATE FILE HERE

instead of

fileName = new File(sdDir, "FlyNote/"+FileName);

Upvotes: 2

Related Questions