我想从SD卡中选择图片并对其进行加密。我对java io异常有一些问题-权限被拒绝。我在android清单READ和WRITE EXTERNAL STORAGE中声明了使用权限,但不起作用
然后我打开设备文件资源管理器并检查权限,所有这些人都没有写权限
我的代码:
File file = new File(uri_result);//create path from uri
final String[] split = file.getPath().split(":");//split the path.
String filePath = split[2];
try {
FileInputStream fis = new FileInputStream(filePath);
File fos_enc = new File( Environment.getExternalStorageDirectory().getAbsolutePath()+"/abcd.jpg");
fos_enc.createNewFile();
FileOutputStream fos = new FileOutputStream(fos_enc);
byte[] k = "123456".getBytes();
SecretKeySpec key = new SecretKeySpec(k,"DES");
Cipher enc = Cipher.getInstance("DES");
enc.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(fos, enc);
byte[] buf = new byte[1024];
int read;
while ((read = fis.read(buf)) != -1) {
cos.write(buf,0,read);
}
fis.close();
fos.flush();
cos.close();
showAlertDialog("Encrypt Successfully");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
权限被拒绝,因为sdcard无法访问写入文件,而且我不知道要解决此问题。请帮助我:)
fos_enc = newFile(Environment.getExternalStorageDirectory()。getAbsolutePath()+“ / abcd.jpg”);
答案 0 :(得分:0)
使用外部存储需要获得用户的许可。您需要在运行时向用户询问。 Check this doc。或在测试应用程序设置中手动访问权限。
答案 1 :(得分:0)
您需要为其添加权限。因为您需要外部文件的读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
您需要先在运行时请求权限,然后再执行以下操作(对于使用棒棒糖的设备以及android os以上的设备,这是必需的)
if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
}
答案 2 :(得分:0)
android:requestLegacyExternalStorage="true" 解决了我的问题