Reputation: 4290
I'm in the process of making an Android application that creates a new file when a button is pressed. I'm using the following code:
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"myDirectory" //folder name
+File.separator
+"myFile.png"); //file name
file.mkdirs();
However, myFile.png
is actually being displayed as a directory and not a .png file.
Upvotes: 2
Views: 328
Reputation: 109237
Because of file.mkdirs();
mkdirs() - is used for making directory by filename given file object's parameter, If you want to make a file make IO operation for writing in a file,
In your case: to make a directory,
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"myDirectory" //folder name
+File.separator
+"myFile.png"); //file name
file.getParentFile().mkdirs();
This make a myDirectory folder in external storage.
Upvotes: 5
Reputation: 30855
file.mkdirs()
the above code will create the new directories.
To create the file
try{
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"myDirectory" //folder name
+File.separator
+"myFile.png"); //file name
myFile.createNewFile();
OutputStream filoutputStream = new FileOutputStream(myFile);
filoutputStream.write(b);
filoutputStream.flush();
filoutputStream.close();
} catch (IOException e) {
// handler exception
}
Upvotes: 1
Reputation: 308061
According to its documentation File.mkdirs()
"creates the directory named by the trailing filename of this file".
In other words: you explictly create a directory named myFile.png
. If that's not what you want, then you probably want to do file.getParentFile().mkdirs()
instead.
Upvotes: 2