什么是最简单的方法从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());

当前回答

使用Kotlin甚至更容易:

val file = File(uri.path)

或者如果你在Android上使用Kotlin扩展:

val file = uri.toFile()

更新: 对于图像,它返回“Uri缺少'file' scheme: content://”

谢谢你的评论

其他回答

使用这个来写入文件,它为我工作时,gif的uri是由GBoard提供的,我必须在我的应用程序数据复制该gif。

    try {
      String destinationFilePath = getExternalFilesDir("gifs") + "/tempFile.txt";
      InputStream inputStream = getContentResolver().openInputStream(uri);
      OutputStream outputStream = new FileOutputStream(destinationFilePath);

      byte[] buffer = new byte[1024];
      int bytesRead;

      while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
      }

      inputStream.close();
      outputStream.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }

@CommonsWare解释得很好。我们真的应该采用他提出的解决方案。

顺便说一下,当查询ContentResolver时,我们唯一可以依赖的信息是文件的名称和大小,如下所述: 检索文件信息| Android开发人员

正如您所看到的,这里有一个接口OpenableColumns,它只包含两个字段:DISPLAY_NAME和SIZE。

在我的例子中,我需要检索关于JPEG图像的EXIF信息,并在发送到服务器之前根据需要旋转它。为此,我使用ContentResolver和openInputStream()将文件内容复制到临时文件中。

这些对我都没用。我发现这是可行的解决方案。但我的情况仅限于图像。

String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();

对于那些在这里寻找图像解决方案的人,特别是在这里。

private Bitmap getBitmapFromUri(Uri contentUri) {
        String path = null;
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            path = cursor.getString(columnIndex);
        }
        cursor.close();
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        return bitmap;
    }

你想要的是…

new File(uri.getPath());

... ,而不是……

new File(uri.toString());

笔记

对于android.net.Uri对象,它被命名为uri并完全按照问题中创建,uri. tostring()返回一个“file:///mnt/sdcard/myPicture.jpg”格式的字符串,而uri. getpath()返回一个“/mnt/sdcard/myPicture.jpg”格式的字符串。 我知道在Android系统中文件存储有一些细微差别。在这个回答中,我的意图是准确地回答提问者所问的问题,而不是深究其中的细微差别。