'Android (Java) - Open a file stored in Downloads/Documents
I want to directly open existing file stored in /Downloads
File will have specific name "terminal_config.json" and will be either local or on SD card.
Path should be like, but I think that's device specific and I cannot explicitly use this (instead use environment variable like "documents"): /storage/emulated/0/Documents/terminal_config.json
How can I do that?
Solution 1:[1]
This is the working code. Thank you for cooperation.
Add this to AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application .........
android:requestLegacyExternalStorage="true">
// will ask for permissions if needed, even though they
// are in AndroidManifest.xml already
verifyStoragePermissions(MainActivity.this);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "terminal_config.json");
Uri path = Uri.fromFile(file);
Log.w(null, "XXXFILE"+file);
try {
Log.w(null, "READ:"+getStringFromFile(file));
}
catch (Exception e) {
Log.d("ERR_FILE", e.toString());
}
And then I copied these functions:
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (File fl) throws Exception {
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
fin.close();
return ret;
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin ZvarÃk |
