I'm searching how to create a file in sd card. Currently I have this code :
public class Store {
private final String fileName = "histoires.json";
public void createFile(Context context, String json) {
File file = new File (getDir(context), fileName);
try {
FileOutputStream out = new FileOutputStream(file);
out.write(json.getBytes());
out.flush();
out.close();
} catch (Exception e) {
Log.e("Erreur enregistrement du fichier", e.toString());
}
}
private File getDir(Context context) {
File dir;
if(!isExternalStorageReadable() || !isExternalStorageWritable()) {
dir = context.getFilesDir();
}
else {
dir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
}
return dir;
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}}
In my activity I just call this :
new Store().createFile(this, json);
Problem is : I see my file but always in phone memory. I used getExternalFilesDir(). Anyway it doesn't want to save my file in SD card.
I checked content of my dir variable in getDir() at return statement and it is :
/storage/emulated/0/Android/data/com.histoire_horreur/files/Documents
Can you please help me ?