PdfBox-Android EPERM(不允许操作)将文档保存到外部存储器时

PdfBox-Android EPERM (Operation not permitted) when saving a document to external storage

更新到 Android 11 后,当 PdfBox-Android 保存新文件时出现“不允许操作”错误:

java.io.FileNotFoundException: /storage/emulated/0/my_folder/file_name.pdf: open failed: EPERM (Operation not permitted)

该应用程序向用户请求存储权限,如果我检查 Android 权限管理器,则允许该应用程序管理所有文件。我尝试使用以下代码将 pdf 保存到应用程序本身创建的文件夹中的外部存储中。

String documentsPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "my_folder";
File directory = new File(documentsPath);
if (!directory.exists()) {
    directory.mkdir();
}

目录创建正确,App可以正常保存其他文件到目录下。例如,我用来保存 CSV 文件的代码如下。

File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "my_folder");
File csvFile = new File(dir + File.separator + "csv_file.csv");
FileOutputStream csvFOut = new FileOutputStream(csvFile, true);
OutputStreamWriter csvOutWriter = new OutputStreamWriter(csvFOut, StandardCharsets.UTF_8);
csvOutWriter.append("CSV CONTENT");
csvOutWriter.close();
csvFOut.close();

然后我可以使用 FileProvider 打开 CSV 文件。 provider-paths.xml文件内容如下

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

但是,当我尝试使用 PdfBox-Android 保存文件时,以下示例中的 PDDocument.save(String fileName) 调用会引发异常。

PDFBoxResourceLoader.init(getActivity());
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.drawString("Text");
contentStream.endText();
contentStream.close();

String documentsPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "my_folder";
String pdfFilePath = documentsPath + File.separator + "file_name.pdf");

doc.save(pdfFilePath);
doc.close();

我是否必须以不同的方式配置 PdfBox-Android?

问题不是由于库引起的,而是由于在应用程序支持的一种语言中,自动生成的文件名的一部分包含不允许的字符。