Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?

后端 未结 3 929
眼角桃花
眼角桃花 2020-11-22 01:13

I\'m working on an Android application where one of the features is to let the user choose a file to open (I\'m wanting to open a plain text .txt file). I\'ve worked on And

3条回答
  •  鱼传尺愫
    2020-11-22 01:43

    If you are getting "msf:xxx" in URI, use below solution where I have created temp file in app cache directory and deleted same file after completion of my task:

    if (id != null && id.startsWith("msf:")) {
                        final File file = new File(mContext.getCacheDir(), Constant.TEMP_FILE + Objects.requireNonNull(mContext.getContentResolver().getType(imageUri)).split("/")[1]);
                        try (final InputStream inputStream = mContext.getContentResolver().openInputStream(imageUri); OutputStream output = new FileOutputStream(file)) {
                            final byte[] buffer = new byte[4 * 1024]; // or other buffer size
                            int read;
    
                            while ((read = inputStream.read(buffer)) != -1) {
                                output.write(buffer, 0, read);
                            }
    
                            output.flush();
                            return file;
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        return null;
                    }
    

    I have fixed this issue and it's working 100% for msf. :)

    Also Delete the temp file after the completion of your work:

    private void deleteTempFile() {
            final File[] files = requireContext().getCacheDir().listFiles();
            if (files != null) {
                for (final File file : files) {
                    if (file.getName().contains(Constant.TEMP_FILE)) {
                        file.delete();
                    }
                }
            }
        }
    

    Here TEMP_FILE value is "temp."

提交回复
热议问题