首页 > 解决方案 > 将 android Uri 转换为 java 文件 Android Studio

问题描述

我的应用程序中有一个 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;
}

标签: javaandroidandroid-studiogoogle-drive-api

解决方案


解决了!

我是这样做的:

        // 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


推荐阅读