I'm attempting to save a JSON string to a file on the 'External' storage. Specifically the Documents folder. This would should be the storage you could access with a file browser, from gmail, or over USB on your computer.
So I followed the documentation here and came up with this: (note, changed to now create directory first, then append filename. Save now attempts to use MediaScanner)
public static File GetDocumentsPath(String tuningName) {
// Get the directory for the user's public pictures directory.
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
if (!dir.mkdirs()) {
Logy.CallPrint("JSONTuning", "Directory not created");
}
File outFile = new File(dir, tuningName);
return outFile;
}
public static String SaveTuning(Context context, String fileName, String json)
{
File path;
if(fileName.contains(".rfts")) {
path = GetDocumentsPath(fileName);
} else {
path = GetDocumentsPath(fileName+".rfts");
}
Logy.Print("|||||||||||||||| "+path.getPath());
try {
FileOutputStream fileOut = new FileOutputStream(path);
ObjectOutput strOut = new ObjectOutputStream(fileOut);
strOut.writeUTF(json);
strOut.close();
fileOut.close();
MediaScannerConnection scanner = new MediaScannerConnection(context, null);
scanner.connect();
if(scanner.isConnected())
scanner.scanFile(path.getPath(), null);
scanner.disconnect();
return "Save Successful";
}
catch(java.io.IOException e) {
return e.getMessage();
}
}
So I logged the path I was getting from GetDocumentsPath. That path would be: /storage/emulated/0/Download/Test.rfts
This does not lead to the file being saved in Documents as far as what I can access via file manager/computer. The fact that the word "emulated" is in there leads me to believe Environment isn't giving me the actual path at all.
I do get the error "/storage/emulated/0/Documents/Test.rfts: open failed: ENOENT (No such file or directory)"
What's needed to get the correct path, and save to, the documents folder in external storage?
As a side note, the way I write the file works perfectly fine for internal storage, as I'm having no issues creating a file with app settings.