Save .txt file on Android Q

我只是一个虾纸丫 提交于 2020-06-01 06:52:32

问题


I was trying to save text file using below code

try {
                FileOutputStream fos = new FileOutputStream(TXT_FILE_NAME, true);

                FileWriter fWriter;

                try {
                    fWriter = new FileWriter(fos.getFD());
                    fWriter.write(binding.tvExtractedResult.getText().toString());
                    fWriter.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    fos.getFD().sync();
                    fos.close();
                    Toast.makeText(this, "File Saved Successfully", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "Error while saving file", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

But the problem is this code doesn't work with Android Q. After this I tried to search the solution and I did this

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues myContentValues = new ContentValues();
            myContentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, TXT_FILE_NAME);
            String myFolder = "Download/MY_PROJECT";
            myContentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, myFolder);
            myContentValues.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
            myContentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);

            Uri extVolumeUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);

            ContentResolver contentResolver = getContentResolver();
            Uri uri = contentResolver.insert(extVolumeUri, myContentValues);

            if (uri == null) {
                Log.e(TAG, "uri is null");
                return;
            }
            Log.e(TAG, "uri=" + uri);

            try {
                FileOutputStream fos = new FileOutputStream(new File(uri.toString()));

                fos.write(binding.tvExtractedResult.getText().toString().getBytes());
                fos.close();
            } catch (Exception e) {
                Log.e(TAG, "error occurred" + e.getMessage());
                e.printStackTrace();
            } finally {
                myContentValues.clear();
                myContentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
                contentResolver.update(uri, myContentValues, null, null);
            }

        }

In above code I'm getting uri == null

Appreciate your help. Thanks.

来源:https://stackoverflow.com/questions/61984396/save-txt-file-on-android-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!