即使提供了运行时读写权限,也无法在SD卡(外部存储)上创建文本文件

时间:2018-09-25 08:35:00

标签: java android

我在AndroidManifest.xml文件中授予了读取和写入外部存储权限,并且还在运行时检查了权限。但仍然无法在SD卡上创建文本文件

下面的代码:

try {

    File dir = new File(getExternalStoragePath() + "/" + IMAGE_DIRECTORY_NAME);
    String path;

    if (!dir.exists())
        dir.mkdirs();

    path = dir.getAbsolutePath();

    showMessage("path: " + path);

    File myFile = new File(path + File.separator + "MyTextFile.txt");

    // Adds a line to the file
    BufferedWriter writer = new BufferedWriter(new FileWriter(myFile, true /*append*/ ));
    writer.write("This is a test file.");
    writer.close();

    Toast.makeText(processTrailerFragmentContext,
        "Done writing SD 'mysdfile.txt'",
        Toast.LENGTH_SHORT).show();
} catch (Exception e) {
    Toast.makeText(processTrailerFragmentContext, "Exception: " + e.getMessage(),
        Toast.LENGTH_SHORT).show();
}



/**
 * Method will return the path of the sd card
 * @return sd card path
 */
public String getExternalStoragePath() {

    String internalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    String[] paths = internalPath.split("/");
    String parentPath = "/";
    for (String s: paths) {
        if (s.trim().length() > 0) {
            parentPath = parentPath.concat(s);
            break;
        }
    }
    File parent = new File(parentPath);
    if (parent.exists()) {
        File[] files = parent.listFiles();
        for (File file: files) {
            String filePath = file.getAbsolutePath();

            Log.d(PROCESS_TRAILER_TAG, filePath);

            if (filePath.equals(internalPath)) {
                continue;
            } else if (filePath.toLowerCase().contains("sdcard")) {
                return filePath;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                try {
                    if (Environment.isExternalStorageRemovable(file)) {
                        return filePath;
                    }
                } catch (RuntimeException e) {
                    Log.e(PROCESS_TRAILER_TAG, "RuntimeException: " + e);
                }
            }
        }

    }
    return null;
}

1 个答案:

答案 0 :(得分:0)

在以下代码段中尝试以下操作:

 File file = new File("/sdcard/textFile.txt");
            FileOutputStream stream = null;
            try {
                stream = new FileOutputStream(file);
                String uristr = "text files content";
                stream.write(uristr.getBytes());               
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }