我需要Android设备上图片的File对象。
我使用函数来获取给定URI的FileInputStream。
FileInputStream getSourceStream(Uri u) throws FileNotFoundException {
FileInputStream out = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(u, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
out = new FileInputStream(fileDescriptor);
} else {
out = (FileInputStream) getContentResolver().openInputStream(u);
}
return out;
}
返回FileInputStream。我需要的是图像的File对象。如何从FileInputStream获取文件?
更新
这就是我获取URI的方式:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
并在onActivityResult
上获取图片的URI。
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(resultCode == RESULT_OK){
String uri = data.getData();
}
}
答案 0 :(得分:4)
您可以使用以下代码将FileInputStream转换为File对象。
try {
File outputFile = new File("YOUR DESIRED FILE PATH");
FileOutputStream fos = new FileOutputStream(outputFile);
int c;
while ((c = fileInputStream.read()) != -1) {
fos.write(c);
}
fileInputStream.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}
这里' fileInputStream'是getSourceStream()返回的对象