什么是最简单的方法从android.net.Uri对象持有一个文件:类型转换为java.io.File对象在Android?
我尝试了下面的方法,但不管用:
File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());
public String getRealPathFromURI(Uri uri)
{
String result;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
result = uri.getPath();
cursor.close();
return result;
}
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
return result;
}
然后使用从URI中获取文件:
File finalFile = newFile(getRealPathFromURI(uri));
——希望能帮到你----
public String getRealPathFromURI(Uri uri)
{
String result;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
result = uri.getPath();
cursor.close();
return result;
}
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
return result;
}
然后使用从URI中获取文件:
File finalFile = newFile(getRealPathFromURI(uri));
——希望能帮到你----
使用内容解析器获取输入流
InputStream inputStream = getContentResolver().openInputStream(uri);
然后将输入流复制到文件中
FileUtils.copyInputStreamToFile(inputStream, file);
样品使用方法:
private File toFile(Uri uri) throws IOException {
String displayName = "";
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
try {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}finally {
cursor.close();
}
}
File file = File.createTempFile(
FilenameUtils.getBaseName(displayName),
"."+FilenameUtils.getExtension(displayName)
);
InputStream inputStream = getContentResolver().openInputStream(uri);
FileUtils.copyInputStreamToFile(inputStream, file);
return file;
}
uri.toString()给我:"content://com.google.android.apps.nbu.files.provider/1/file%3A%2F%2F%2Fstorage%2Femulated%2F0%2FDownload%2Fbackup.file"
uri.getPath()给我:“/1/文件:///存储/模拟/0/下载/备份文件。”
new File(uri.getPath())给我“/1/ File:/storage/ emululated /0/Download/backup.file”。
所以如果你有一个文件的访问权限,想要避免使用ContentResolver或直接读取文件,答案是:
private String uriToPath( Uri uri )
{
File backupFile = new File( uri.getPath() );
String absolutePath = backupFile.getAbsolutePath();
return absolutePath.substring( absolutePath.indexOf( ':' ) + 1 );
}
为简化回答,跳过错误处理