GVillani82
GVillani82

Reputation: 17439

Android: error creating file in a not previus created directory

I' m trying to download a file named flower.jpg

 String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/flower.jpg";

 File f = new File(fileName);
 if(!f.exists())
 {
      f.createNewFile();
 }
 DataOutputStream fos = new DataOutputStream(new FileOutputStream(f));
    fos.write(buffer);
    fos.flush();
    fos.close();

that works pretty good.

But I want put my file in a new directory (images) , that does not exist yet. And If I try with

 String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images/flower.jpg";

I obtain:

 11-06 18:19:01.570: W/System.err(17601): java.io.IOException: No such file or directory
 11-06 18:19:01.580: W/System.err(17601):   at java.io.File.createNewFileImpl(Native Method)
 11-06 18:19:01.580: W/System.err(17601):   at java.io.File.createNewFile(File.java:1115)

Upvotes: 0

Views: 555

Answers (2)

MByD
MByD

Reputation: 137442

You need to create a directory first:

String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images";
File dir = new File(dirName);
if(!d.exists())
{
     d.mkdirs();
}

String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images/flower.jpg";

File f = new File(fileName);
if(!f.exists())
{
     f.createNewFile();
}

Upvotes: 0

asloob
asloob

Reputation: 1326

You need to check whether directory 'images' exists and if not create it.

    if (isMediaMounted()) {

                File cnxDir = new File(
                        Environment.getExternalStorageDirectory()
                                + File.separator + "folderName");
                if (!cnxDir.exists()) {

                    cnxDir.mkdir();

                }}

//

 private boolean isMediaMounted() {
    if (Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState())) {
        return true;
    } else {
        return false;
    }
}

Upvotes: 1

Related Questions