java - 使用 Google Drive API 获取文件大小

标签 java google-drive-api filesize

我正在尝试列出来自 Google 云端硬盘的文件及其适用于我的应用程序的大小,下面是我尝试获取大小的方法

File file = service.files().get(file.getId()).setFields("size").execute();
file.getSize()

我开始知道从这次调用中获得的大小不正确,因为谷歌驱动器仅填充除谷歌文档、工作表 Get size of file created on Google drive using Google drive api in android 之外的文件的文件大小。

我还尝试通过 http GET 来确定文件的大小 webContentLink 并检查 Content-Length header ,如下所示

HttpURLConnection conn = null;
        String url = "https://docs.google.com/a/document/d/1Gu7Q2Av2ZokZZyLjqBJHG7idE1dr35VE6rTuSii36_M/edit?usp=drivesdk";
        try {
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("HEAD");
            conn.getInputStream();
            System.out.println(conn.getContentLength());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

但在这种情况下,文件大小不正确,因为它非常大

有什么方法可以确定文件大小吗?

最佳答案

找到问题的解决方案。对于上传到谷歌驱动器的文件,可以通过调用 file.getSize() 确定文件大小。对于 Google 应用程序文件,例如文档、电子表格等,file.getSize() 将返回 null,因为它们不占用驱动器中的任何空间。因此,作为一种黑客方式,我将其导出为 pdf 并确定大小。下面是代码

try {
            Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                        .setApplicationName("xyz")
                        .build();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            service.files().export(fileId, "application/pdf")
                .executeMediaAndDownloadTo(outputStream);
            int fileSize = outputStream.toByteArray().length;
        } catch (Exception ex) {

        }

关于java - 使用 Google Drive API 获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870306/

相关文章:

jquery - 使用 jQuery 查找下载链接后面的文件大小

android - 如何在Android中复制大文件?

java - 确定一个方法是否使用反射覆盖另一个方法?

java - 具有弱引用值而不是键的 WeakHashMap

java - HTTPURLConnection Getoutputstream 挂起

google-docs-api - Google Drive API 是否支持上传内容范围?

ios - 是否可以从 IOS sdk 中的 Dropbox 和 Google Drive 文件应用程序获取文件

java - 在Google上实现操作

android - 为 Android 应用程序同步数据库

java - 在 Java 中比较图像大小(以 KB 为单位)