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

当前回答

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 );
}

为简化回答,跳过错误处理

其他回答

使用这个来写入文件,它为我工作时,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();
    }

使用

InputStream inputStream = getContentResolver().openInputStream(uri);    

直接复制文件。还看到:

https://developer.android.com/guide/topics/providers/document-provider.html

如果你有一个符合DocumentContract的Uri,那么你可能不想使用File。 如果你在kotlin上,使用DocumentFile来做你在旧世界中使用File来做的事情,并使用ContentResolver来获取流。

其他的东西几乎都肯定会坏。

科特林 2022

suspend fun Context.createFileFromAsset(assetName: String, fileName: String): File? {
    return withContext(Dispatchers.IO) {
        runCatching {
            val stream = assets.open(assetName)
            val file = File(cacheDir.absolutePath, fileName)
            org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, file)
            file
        }.onFailure { Timber.e(it) }.getOrNull()
    }
}

处理完文件后,请确保对其调用.delete()。向@Mohsent致敬

我是这样做的:

try {
    readImageInformation(new File(contentUri.getPath()));

} catch (IOException e) {
    readImageInformation(new File(getRealPathFromURI(context,
                contentUri)));
}

public static String getRealPathFromURI(Context context, Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj,
                null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
}

所以基本上首先我尝试使用一个文件,即相机拍摄的照片,并保存在SD卡上。这对返回的图像不起作用: 意图photoPickerIntent =新的意图(Intent. action_pick); 在这种情况下,需要通过getRealPathFromURI()函数将Uri转换为真实路径。 所以结论是,这取决于你想转换为File的Uri类型。