Reputation: 803
My App creates and use some images from the sd-card. These images are shown in the gallery of the device, but i dont want that. So i tried to create a .nonmedia file in this directory, but my problem is that this file wont be created.
Heres the code:
public void createNonmediaFile(){
String text = "NONEMEDIA";
String path = Environment.getExternalStorageDirectory().getPath() + "/" + AVATARS + "/.nonmedia";
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
There are no exceptions.
I gues it has something to do with the "." in the name. If i try the same whithout it, the file gets created.
Thanks for your help.
Upvotes: 0
Views: 577
Reputation: 2171
Put below permission in your android-manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And then below code should work just fine:
private static final String AVATARS = "avatars";
public void createNonmediaFile(){
String text = "NONEMEDIA";
String path = Environment.getExternalStorageDirectory().getPath() + "/" + AVATARS + "/.nonmedia";
String f = Environment.getExternalStorageDirectory().getPath() + "/" + AVATARS ;
FileOutputStream fos;
try {
File folder = new File(f);
boolean success=false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (true==success) {
File yourFile = new File(path);
if(!yourFile.exists()) {
yourFile.createNewFile();
}
} else {
// Do something else on failure
}
fos = new FileOutputStream(path);
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 2409
Try using the following example
File file = new File(directoryPath, ".nomedia");
if (!file.exists()) {
try {
file.createNewFile();
}
catch(IOException e) {
}
}
Upvotes: 1