Android将base64图像保存到SDCARD上的文件中

时间:2017-02-28 06:37:18

标签: android

当我尝试将base64字符串包含到SD-CARD的文件中时,我收到错误或我使用过的方法不能正常工作;

File file = new File(Ketabkhan.IMAGE);
if (!file.exists()) {
    file.mkdirs();
}
if (shabek.length() < 1)
    shabek = "test";
base64FileName = shabek.replace("-", "") + ".png";
fos = new FileOutputStream(new File(Ketabkhan.IMAGE + "/" + base64FileName), true);
byte[] decodedString = android.util.Base64.decode(tasvirData, android.util.Base64.DEFAULT);
fos.write(decodedString);
fos.flush();
fos.close();

在上面的代码和这一行:

fos = new FileOutputStream(new File(Ketabkhan.IMAGE + "/" + base64FileName), true);

创建空文件,但在使用此代码后代替:

fos = context.openFileOutput(Ketabkhan.IMAGE + "/" + base64FileName, Context.MODE_PRIVATE);

我收到此错误:

File /storage/emulated/0/Ketabkhan/images/test.png contains a path separator

授予权限并

if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    parseSelectedBookContains();
} else {
    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_PERMISSION);
}

返回true并parseSelectedBookContains()正常工作

1 个答案:

答案 0 :(得分:0)

您无法在openFileOutput方法中使用路径分隔符。它可以包含文件的名称,但不包含路径分隔符。 有关详细信息,请参阅 https://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)