androniennn
androniennn

Reputation: 3137

Want to create a file, a directory created instead !

I'm using this code to create a file in the root of sdcard, however, i have a directory created instead of "fileDir+fileName" !

File file = new File(sdCard.getAbsolutePath(), fileDir+fileName);
    if (!file.mkdirs()) {

        Log.d("ERROR", "Create dir in sdcard failed");

        return;
    }
        OutputStream out = new FileOutputStream(file);
..............................

Thank you for your help.

Upvotes: 0

Views: 841

Answers (3)

Phil Lello
Phil Lello

Reputation: 8639

If you're expecting file.mkdirs() to create the directory for the file, then you need to tweak it slightly to file.getParentFile().mkdirs()

Of course, this should be wrapped in a try/catch clause, in case getParentFile() returns null

Hope this helps,

Phil Lello

Upvotes: 0

Priyank
Priyank

Reputation: 10623

file.mkdirs() creates directory and not the file [Ref: http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdir(). This is the code which creates directory. you should use code something like this.

 String destination = currentdir + "test.txt"; 
        File fileCon = new File(destination); 
        if( ! fileCon.exists() ){ 
                fileCon.createNewFile(); 
            } 

Alternatively try this,

     String destination = currentdir + "test.txt"; 


// Open output stream
            FileOutputStream fOut = new FileOutputStream(destination);

            fOut.write("Test".getBytes());

            // Close output stream
            fOut.flush();
            fOut.close();

Upvotes: 2

chris polzer
chris polzer

Reputation: 3367

file.mkdirs() is generating the directory structure in your if clause. You could test if you are able to write by file.canWrite(), I suppose.

Documentation is here.

Since you say, it is generating directories, it should return true, but the important part is not shown here:)

Upvotes: 1

Related Questions