首页 > 解决方案 > Android 10 不保存文本文件

问题描述

我生成了一个文本文件并尝试保存它。它不仅适用于 android Q。在 android 9 、 8 和 7 上它有效。当我检查文件是否存在于 android 10 上时,它可以工作,但我不在设备上。我这样做:

private void createFile(Context ctx, String fileName, String text) {
    File filesDir = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        filesDir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
    }
    assert filesDir != null;
    if (!filesDir.exists()){
        if(filesDir.mkdirs()){
        }
    }
    File file = new File(filesDir, fileName + ".txt");
    try {
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("Cant able to create file");
            }
        }
        OutputStream os = new FileOutputStream(file);
        byte[] data = text.getBytes();
        os.write(data);
        os.flush();
        os.close();
        Log.e("TAG", "File Path= " + file.toString());
        if(file.exists()){
            Log.e("d","d");
        }
        File fileTemp = new File(file.getPath());
        FileInputStream notes_xml = new FileInputStream(fileTemp);
        byte fileContent[] = new byte[(int)notes_xml.available()];
//The information will be content on the buffer.

        notes_xml.read(fileContent);

        String strContent = new String(fileContent);
        Log.e("content",strContent);
        notes_xml.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

标签: javaandroid

解决方案


推荐阅读