我有一个问题。我尝试下载一个 pdf 文件并将该文件保存在我的应用程序文件夹中。但是当我尝试这样做时,出现错误并且文件未保存...
这是我的提供商
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="Android/data/xxx/files/Download" />
</paths>
我把它放在 list 中
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="xxx.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths2" />
</provider>
我这样做:
public static void parseBase64ToPDFAndNoOpen(String base64, String cardId ,Context context) throws IOException {
FileOutputStream os;
String path;
Uri photoURI = null;
try {
photoURI = FileProvider.getUriForFile(context.getApplicationContext(),
BuildConfig.APPLICATION_ID + ".provider", createImageFile(context,cardId));
} catch (IOException e) {
e.printStackTrace();
}
File dwldsPath = new File(photoURI.toString());
// File dwldsPath = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + cardId + ".pdf");
if (!dwldsPath.exists()) {
dwldsPath.createNewFile();
byte[] pdfAsBytes = Base64.decode(base64, 0);
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
}
}
private static File createImageFile(Context context,String name) throws IOException {
File imagesDir = new File(getDefaultTempFilesPath(context));
return File.createTempFile(
name, /* prefix */
".pdf", /* suffix */
imagesDir /* directory */
);
}
private static String getDefaultTempFilesPath(Context context) {
if (context != null) {
File f = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (f != null)
return f.getPath();
else {
f = context.getFilesDir();
if (f != null)
return f.getPath();
}
}
return null;
}
我有:java.io.IOException:没有这样的文件或目录
最佳答案
确保您已在 list 中添加写入外部存储权限。
或引用how to save a downloaded file into internal storage in android?
希望该链接能有所帮助。
关于java - 下载并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713775/