前言
思路:文件类型是String类型的Base64字符串,然后将其转成byte[]类型后保存在本地,最后调用Intent方法打开文件。
保存文件的方法
private void saveFile(String base64Data, String fileName) {
// 解码base64Data为字节数组
byte[] data = Base64.decode(base64Data, Base64.DEFAULT);
// 将字节数组转换为Excel文件并保存到本地
try {
String path = Environment.getExternalStorageDirectory() // 文件保存的路径
File file = new File(path, fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
toastMsg("文件保存成功!");
openFile(file);
} catch (IOException e) {
e.printStackTrace();
toastMsg("文件保存失败!");
}
}
打开文件的方法
// 应用程序的FileProvider授权
String provider = "com.pft.smartwater.fileProvider";
Uri uri = FileProvider.getUriForFile(this, provider, file);
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
toastMsg("未查找到能打开该文件的应用程序,请手动前往打开文件。文件目录:" + file.getPath());
}
引用程序的授权
这个是在AndroidManifest.xml中定义的FileProvider的授权名称(authorities的内容)。
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.pft.smartwater.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepath" />
</provider>