Create File at Same Location as User Selected Uri

4 days ago 8
ARTICLE AD BOX

How can I create a file in the same location as a Uri obtained from user selection (but with different extension), in that the selected file may not always be in the same folder on the device (could be in Documents, Download, etc).

Specifically, the intent is:

- Use selects MyFolder/Test.jpg (in this example, MyFolder is in the device's Documents folder).

- App loads and analyzes image

- App saves results as MyFolder/Test.dat (creating this file is the problem)

The source images will be located in one of the Environment folders (Environment.DIRECTORY_DOCUMENTS, Environment.DIRECTORY_DOWNLOADS, Environment.DIRECTORY_PICTURES, etc.), but I won't know which one until the user chooses the file, and I don't know how to reliability extract that information from the selected uri. Multi-threading/error handling omitted for clarity.

//Load image routine public void onLoadImage () { mFileLoader.launch(new String[]{"image/jpeg"}); } //User has selected image (location contained in uri) ActivityResultLauncher<String[]> mFileLoader = registerForActivityResult( new ActivityResultContracts.OpenDocument(), uri -> { // Load image from file using uri (works) // Perform processing on loaded image // App has analyzed image and attempting to create results file File dstFile; // Convert to String // srcString = content://com.android.externalstorage.documents/document/primary%3ADocuments%2FMyFolder%2FTest.jpg String srcString = uri.toString(); //Change Extension // dstString = content://com.android.externalstorage.documents/document/primary%3ADocuments%2FMyFolder%2FTest.dat String dstString = srcString.replace(".jpg",".dat"); //Attempt 1: Create Uri from string and use content resolver // Fails: java.lang.SecurityException Uri dstUri = Uri.parse(dstString); OutputStream os = getContentResolver().openOutputStream (dstUri); if (os != null) os.close (); //Attempt 2: Hard code dst location //Works, but location is hard coded, not dependent on user selected file or location dstString = "/storage/emulated/0/Documents/MyFolder/Test.dat"; dstFile = new File (dstString); dstFile.createNewFile(); //Attempt 3: Assumes file is in Documents folder // Works, but assumes file came from Documents folder File dstFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS); dstFile = new File(dstFolder.getPath(), "MyFolder/Test.dat"); dstFile.createNewFile(); });
Read Entire Article