在Android 13中,你可以使用以下代码将PDF保存到外部存储:
private void savePdfToExternalStorage(File pdfFile) {
// 获取外部存储的目录
File externalStorageDir = Environment.getExternalStorageDirectory();
// 创建一个文件夹用于保存PDF
File pdfDir = new File(externalStorageDir, "PDFs");
if (!pdfDir.exists()) {
pdfDir.mkdirs();
}
// 创建一个新的文件来保存PDF
File newFile = new File(pdfDir, pdfFile.getName());
try {
// 复制PDF文件到新的文件中
InputStream in = new FileInputStream(pdfFile);
OutputStream out = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
// 在日志中打印保存的文件路径
Log.d("PDF", "Saved to: " + newFile.getAbsolutePath());
// 如果需要,在这里更新你的UI或执行其他操作
} catch (IOException e) {
e.printStackTrace();
}
}
File pdfFile = new File("path/to/your/pdf.pdf");
savePdfToExternalStorage(pdfFile);
请确保将"path/to/your/pdf.pdf"替换为你想要保存的PDF文件的实际路径。