我在Android应用程序的原始目录中保留了一些二进制文件。我想在应用程序中访问它们并在运行时从它创建一个文件。我打算通过网络发送这个文件。
我如何参考原始资源?我已经完成了以下代码
private File getFileByResourceId(int id, String fileName) throws IOException {
File file = new File(fileName);
InputStream ins = ctx.openRawResource(id);
log.debug(ins.toString());
log.debug(file.getAbsolutePath());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int size = 0;
// Read the entire resource into a local byte buffer.
byte[] buffer = new byte[1024];
while ((size = ins.read(buffer, 0, 1024)) >= 0) {
outputStream.write(buffer, 0, size);
}
ins.close();
buffer = outputStream.toByteArray();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.close();
return file;}
但是当我尝试访问此文件时,它会向我提供权限错误。
有人可以提出解决方案吗?
答案 0 :(得分:0)
您已在Manifestfile中添加此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
您正在使用Marshmallow操作系统,然后您需要添加运行时权限
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG, "Permission is granted");
return true;
}
}