【问题标题】:Convert android Uri to java File Android Studio将 android Uri 转换为 java 文件 Android Studio
【发布时间】:2021-01-20 16:07:18
【问题描述】:

我的应用程序中有一个 ACTION_GET_CONTENT 意图,我需要将选择的文件(会有不同的文件、ppt、doc...)放在 java.io 文件中。

我能够获取数据并将其放入 android.net Uri。有没有办法从这个 Uri 创建一个 java 文件?

我需要它是一个文件,以便使用谷歌驱动器 API 将它上传到谷歌驱动器

这是上传到驱动器的代码,我需要将uri转换为临时文件,以便将其作为该方法的javaFile传递

 public Task<File> uploadFileWithMetadata(java.io.File javaFile, boolean isSlide,  @Nullable final String folderId, PostFileHolder postFileHolder) {
        return Tasks.call(mExecutor, () -> {

            Log.i("upload file", "chegou" );

            String convertTo; // string to convert to gworkspace
            if(isSlide){
                convertTo = TYPE_GOOGLE_SLIDES;
            }
            else{
                convertTo = TYPE_GOOGLE_DOCS;
            }

            List<String> folder;
            if (folderId == null) {
                folder = Collections.singletonList("root");
            } else {
                folder = Collections.singletonList(folderId);
            }

            File metadata = new File()
            .setParents(Collections.singletonList(folderId))
            .setName(postFileHolder.getDisplayName())
            .setMimeType(convertTo);

            Log.i("convert to: ", convertTo );

            // the convert to is the mimeType of the file, withg gworkspace it is a gdoc or gslide, with others is the regular mimetype
            FileContent mediaContent = new FileContent(postFileHolder.getConvertTo(), javaFile);

            Log.i("media content", "chegou" );
            // até aqui com gworkspace chega
            File uploadedFile = mDriveService.files().create(metadata, mediaContent)
                    .setFields("id")
                    .execute();

            Log.i("File ID: " , uploadedFile.getId());

            return uploadedFile;
        });
}

这是我获取 Uri 的代码

 case REQUEST_CODE_FILE_PICKER:

                    // get uri from file picked
                    Uri url = data.getData();
                    break;
}

【问题讨论】:

  • 考虑使用FileUtils
  • 我试过了,没用:(
  • need to storage the picked file 不清楚你想要什么。该文件已存储。否则无法采摘。
  • @blackapps 你好!刚刚更新了问题!我需要的是使用用户选择的文件创建一个 jav.io 文件
  • 您不需要文件实例来上传到谷歌驱动器。您可以使用该 uri。

标签: java android android-studio google-drive-api


【解决方案1】:

解决了!

我是这样做的:

        // my uri
        Uri fileUri = Uri.parse(postFileHolder.getFileUri());
        
        // create a null InputSream
        InputStream iStream = null;
        try {
            // create a temporary file
            File fileToUpload = File.createTempFile("fileToUpload", null, this.getCacheDir());
          
            iStream = getContentResolver().openInputStream(fileUri);
            
           // use function to get the bytes from the created InputStream
            byte[] byteData = getBytes(iStream);

            convert byteArray to File
            FileOutputStream fos = new FileOutputStream(fileToUpload);
            fos.write(byteData);
            fos.flush();
            fos.close();

            if(fileToUpload == null){
                Log.i("create file", "null");
            }
            else{
                Log.i("create file", "not null:  "+ fileToUpload.getTotalSpace());
                getEGDrive(fileToUpload);
            }
}
 catch (FileNotFoundException e) {
                Log.i("error create file uri", e.getLocalizedMessage());

                e.printStackTrace();
            } catch (IOException e) {
                Log.i("error create file uri", e.getLocalizedMessage());

                e.printStackTrace();
            }

这是将 InputStream 转换为 byteArray 的函数:

 public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

大部分答案来自:https://stackoverflow.com/a/10297073/14990708

【讨论】:

  • getContentResolver().openInputStream(fileUri) 这一切都不需要,因为您可以使用您在 onActiviltyResult 中获得的 ACTION_GET_CONTENT 中的 uri,例如 getContentResolver().openInputStream(data.getData())。扔掉那些文件转换的东西。
  • @blackapps 这真的好多了!有没有办法可以将此文件传递给另一个活动?因为我会在一个活动中上传文件,并在下一个活动中实际保存
  • 是的,将字符串 data.getData().toString() 作为额外的字符串放在启动该活动的意图中。但可能读取文件的权限在那里无效。如果是这样,请更改为 ACTION_OPEN_DOCUMENT 并首先获取持久化 uri 权限。
  • @blackapps 如何将 getContentResolver().openInputStream(data.getData()) 放入文件中?
  • 不清楚您遇到的问题。请在您拥有或调用该代码的地方显示您的 onActivityResult 代码。我们想看看你是如何从那里开始的。
猜你喜欢
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 2016-02-13
  • 2015-02-20
  • 1970-01-01
相关资源
最近更新 更多