【问题标题】:Struggling with Scoped Storage - how would I write a plain text file in app directory in Java?挣扎于范围存储 - 我如何在 Java 的应用程序目录中编写纯文本文件?
【发布时间】:2022-01-09 01:36:00
【问题描述】:

我正在将我们的应用程序迁移到 API 版本 30,但我完全在 Scoped Storage 上苦苦挣扎。我想知道,如何使用 Scoped Storage 在 app 目录中编写纯文本文件?我目前正在使用 FileWriter,我想知道如何将其更改为 Scoped Storage。我想要我的 Java 示例,而不是 Kotlin。

【问题讨论】:

  • 什么是“应用目录”?
  • 我应该使用 Scoped Storage 编写的应用程序特定目录。
  • 我假设您的意思是 getExternalFilesDir(null) 上的 Context。这将返回一个指向该目录的 File 对象。从那里开始,就是普通的 Java 文件 I/O。

标签: java android scoped-storage


【解决方案1】:

使用位置

context.getFilesDir()+"/YourFolderName";

在这里你可以存储任何你想要的文件,无需任何许可, 如果您想将文档文件存储在公开可用的位置,请使用此位置,您也不需要任何权限

  try {
        inputStream = //your input stream here;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


    ContentResolver resolver = ctx.getContentResolver();
    ContentValues values = new ContentValues();

    values.put(MediaStore.MediaColumns.DISPLAY_NAME, "My Document name");
        values.put(MediaStore.MediaColumns.MIME_TYPE,"application/*");


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + File.separator + "my app folder/");
    }

    Uri fileUri = resolver.insert(MediaStore.Files.getContentUri("external"), values);      
    try {
        fos = resolver.openOutputStream(fileUri);
        Objects.requireNonNull(fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        byte[] buf = new byte[1024];
        int len;
        while ((len = inputStream.read(buf)) > 0) {

            fos.write(buf, 0, len);
        }

        fos.close();
        inputStream.close();
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.d("TAG", "Exception" + e.getMessage());
        e.printStackTrace();
    }

我包含了第二种方法的代码 bcz 我觉得“MediaStore”可能会让你感到困惑!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2016-11-10
    • 2015-09-08
    • 2019-01-18
    • 2023-04-06
    • 2014-08-30
    相关资源
    最近更新 更多