谷歌驱动器上传文件,读取文件

问题描述:

净家伙在一个Java应用程序谷歌驱动器上传文件,读取文件

我用下面的例子作为我的出发点上传的工作(我有这方面的工作)。这显示了使用FileContent需要一个java.io.File,它不包含实际文件只是一个指向实际文件的指针。

我们从一个网站上传并尝试插入驱动器,我宁愿使用像.Net示例一样的内存流来执行此操作。我看不到在FileContent类。所以我的任务是:有没有办法将文件插入内存中的Google驱动器中,而不是先在硬盘上插入?

private static File insertFile(Drive service, String title, String description, 
    String parentId, String mimeType, String filename) { 
// File's metadata. 
File body = new File(); 
body.setTitle(title); 
body.setDescription(description); 
body.setMimeType(mimeType); 

// Set the parent folder. 
if (parentId != null && parentId.length() > 0) { 
    body.setParents(
     Arrays.asList(new ParentReference().setId(parentId))); 
} 

// File's content. 
java.io.File fileContent = new java.io.File(filename); 
FileContent mediaContent = new FileContent(mimeType, fileContent); 
try { 
    File file = service.files().insert(body, mediaContent).execute(); 

    // Uncomment the following line to print the File ID. 
    // System.out.println("File ID: " + file.getId()); 

    return file; 
} catch (IOException e) { 
    System.out.println("An error occured: " + e); 
    return null; 
} 
} 

覆盖的AbstractInputStream建立自己的FileContent

package com; 

import java.io.IOException; 
import java.io.InputStream; 
import com.google.api.client.http.AbstractInputStreamContent; 
import com.google.api.client.util.Preconditions; 

public class FileContent extends AbstractInputStreamContent { 

private InputStream inputStream = null; 
private long inputLength = 0; 

public FileContent(String type, InputStream pInputStream) throws IOException { 
    super(type); 
    this.inputStream = Preconditions.checkNotNull(pInputStream);   
    this.inputLength = this.inputStream.available(); 
} 

public long getLength() throws IOException { 
    return this.inputLength; 
} 

public boolean retrySupported() { 
    return false; 
} 

@Override 
public InputStream getInputStream() throws IOException { 
    return this.inputStream; 
} 
}