谷歌驱动器 - java.io.FileNotFoundException:document.txt(没有这样的文件或目录)

时间:2015-05-19 07:36:09

标签: java google-drive-api

我正在使用Google Drive API示例中的代码在Drive中插入一个文件,该文件因java.io.FileNotFoundException而失败:document.txt(没有此类文件或目录)。我已经注释掉了在Drive中创建文件夹的代码,这没有任何问题。所以我认证好了。我哪里错了。

亲切的问候, 伊恩。

public void saveToDrive(ServletContext sc){
        GoogleCredential googleCredential = getGoogleApiCredential(sc);
        Drive service = getDriveService(googleCredential);
        String parentId = null;
        try {
            About about = service.about().get().execute();
            System.out.println("Current user name: " + about.getName());

            System.out.println("Root folder ID:" + about.getRootFolderId());
            parentId = about.getRootFolderId();
            System.out.println("Total quota (bytes): " + about.getQuotaBytesTotal());
            System.out.println("Used quota (bytes): " + about.getQuotaBytesUsed());
    }catch (IOException e){

    }

        File body = new File();
        body.setTitle("Doc title");
        body.setDescription("A toast document");
        body.setMimeType("application/vnd.google-apps.file");
        body.setParents(Arrays.asList(new     ParentReference().setId(parentId)));


        java.io.File fileContent = new java.io.File("document.txt");
        FileContent mediaContent = new FileContent("plain/text", fileContent);
            //File body = new File();
            //body.setTitle("title");
            //body.setMimeType("application/vnd.google-apps.folder");


        try {
            //File file = service.files().insert(body).execute();
            File file = service.files().insert(body, mediaContent).execute();

            logger.severe("File id: " + file.getId());
        } catch (IOException e) {

        logger.severe(e.toString());
        }


    }

1 个答案:

答案 0 :(得分:0)

我没有时间完全重新运行您的方案,但您可以使用我使用的方法测试它(因此它已经过测试)。唯一明显的区别是我在“正文”和“内容”中都使用了相同的MIME类型。你的不同。另外我不知道你的'about.getRootFolderId()'产生了什么。您可以尝试在那里粘贴“root”字符串来测试它。

/**********************************************************************
   * create file/folder in GOODrive
   * @param prnId  parent's ID, (null or "root") for root
   * @param titl  file name
   * @param mime  file mime type (optional)
   * @param file  file (with content) to create
   * @return      file id  / null on fail
   */
  static String create(String prnId, String titl, String mime, java.io.File file) {
    String rsid = null;
    if (mGOOSvc != null && titl != null && file != null) {
      File meta = new File();
      meta.setParents(Arrays.asList(new ParentReference().setId(prnId == null ? "root" : prnId)));
      meta.setTitle(titl);
      if (mime != null)
        meta.setMimeType(mime);

      File gFl = mGOOSvc.files().insert(meta, new FileContent(mime, file)).execute();
      if (gFl != null && gFl.getId() != null) 
        rsid = gFl.getId();
    }
    return rsid;
  }

这是从CRUD demo工作的。{ 祝你好运