我设置了一个首选项,让用户使用存储访问框架为我的应用程序选择保存文件夹。获取uri后onActivityResult
我将其保存到SharedPreferences
作为字符串并在要保存时保存图像。
我正在使用此方法成功保存图像。
public void saveImageWithDocumentFile(String uriString, String mimeType, String name) {
isImageSaved = false;
try {
Uri uri = Uri.parse(uriString);
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri);
DocumentFile file = pickedDir.createFile(mimeType, name);
OutputStream out = getContentResolver().openOutputStream(file.getUri());
isImageSaved = mBitmap.compress(CompressFormat.JPEG, 100, out);
out.close();
} catch (IOException e) {
throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
}
Toast.makeText(MainActivity.this, "Image saved " + isImageSaved, Toast.LENGTH_SHORT).show();
}
如果用户删除使用 SAF 选择的文件夹,iget nullDocumentFile file
和应用程序崩溃。我的第一个问题是如何在不再次打开 SAF ui 的情况下检查文件夹是否存在。
我还想使用 ParcelFileDescriptor 通过此方法保存相同的图像
public void saveImageWithParcelFileDescriptor(String folder, String name) {
if (mBitmap == null) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
return;
}
String image = folder + File.separator + name + ".jpg";
Toast.makeText(MainActivity.this, "image " + image, Toast.LENGTH_LONG).show();
Uri uri = Uri.parse(image);
ParcelFileDescriptor pfd = null;
FileOutputStream fileOutputStream = null;
try {
pfd = getContentResolver().openFileDescriptor(uri, "w");
fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
mBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pfd != null) {
try {
pfd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Image saved " + isImageSaved, Toast.LENGTH_SHORT).show();
}
i get java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/612E-B7BF%3Aname/imagePFD.jpg
在线的pfd = getContentResolver().openFileDescriptor(uri, "w");
我就是这样称呼这个方法的当前文件夹是我使用意图和第一种方法中的相同文件夹获得的文件夹。
saveImageWithParcelFileDescriptor(currentFolder, "imagePFD");
我该如何解决这个问题,哪种方法更可取,为什么?