WmBurkert
WmBurkert

Reputation: 295

android writing to sdcard

I am not able to write to the SDCARD. I can not create a Directory or a File, what am I missing I have this in the manifest

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

And this in my code

btnSave.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View arg0) 
            {   
                // Create a directory; all ancestor directories must exist
                    boolean success = (new File("/sdcard/Methods/")).mkdirs();
                //create file   
                    try{
                    File myFile = new File("/sdcard/Methods/Method 1 Square.xml");
                    File file = myFile;
                        // Create file if it does not exist
                        boolean success1 = file.createNewFile();}   
                    catch (IOException e) 
                        {}
                //write to file
                    try {
                        BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/Methods/Method 1 Square.xml"));
                        out.write ("<?xml version=\"1.0\"?>");
                        out.write ("<?mso-application progid=\"Excel.Sheet\"?>");
                        out.write ("Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
                        out.close();
                    } // end try
                    catch (IOException e) 
                    {
                    } // end catch

            } // end public

        }); // end SAVE Button

Upvotes: 1

Views: 467

Answers (2)

Mister Smith
Mister Smith

Reputation: 28199

The problem may be that the directories in the path do not exist. With that FileWriter constructor, if the file does not exist it is created but that doesn't include the directories.

Upvotes: 1

Paresh Mayani
Paresh Mayani

Reputation: 128448

1st Thing:

Just check the 'success' variable, whether it returns really true.

2nd Thing:

As you have hard coded the /sdcard, Instead i suggest you get the directory using: Environment.getExternalStorageDirectory() because in some devices the sd-card root directory is /mnt/sdcard so the above method to get root directory.

3rd Thing:

You should first check whether the SD-card is mounted or not.

Example:

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/dir/subdir");  // in your case, just give /Methods

dir.mkdirs();
File file = new File(dir, "filename");  // in your case, just give "Method 1 Square.xml"

FileOutputStream f = new FileOutputStream(file);

Upvotes: 4

Related Questions