首先,需要将Base64字符串解码为字节数组,然后将字节数组写入文件。在Android中,可以使用Base64.decode()方法来解码字符串,并使用FileOutputStream指定文件路径和名称来写入字节数组数据。
以下是一个示例代码,演示如何将Base64字符串解码为PDF并将其下载到本地存储中:
public void downloadPDF(String base64String) {
// 解码Base64字符串为字节数组
byte[] pdfAsBytes = Base64.decode(base64String, Base64.DEFAULT);
// 将PDF字节数组写入文件
File pdfFile = new File(getExternalFilesDir(null), "example.pdf");
try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
fos.write(pdfAsBytes);
} catch (IOException e) {
e.printStackTrace();
}
// 打开PDF文件
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileprovider", pdfFile);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
在上面的代码中,使用FileProvider来访问存储在外部存储器中的PDF文件。因此,需要在AndroidManifest.xml文件中指定提供者。您可以在
在上述示例中,还需创建并添加file_paths.xml文件,以指定PDF文件的存储路径。例如: