我正在尝试下载我的Google云端硬盘帐户上的所有可用文件,但是下载的文件只包含与原始文件相比所写文本的一部分。我通过阅读Google Drive和Stackoverflow帖子中的不同帖子使我的代码工作,所以可能是我做错了,我无法发现。我正在制作桌面应用程序。 这是我实施的代码。
public class CMDApp {
private static String CLIENT_ID = "CLIENT_ID";
private static String CLIENT_SECRET = "Client_Secret";
private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
// private static String REDIRECT_URI = "http://localhost/authCode";
public static void main(String[] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
//System.out.println("Please open the following URL in your browser then type the authorization code:");
JOptionPane.showMessageDialog(null,"After you click \"OK\" button,\n You will be taken to Google Drive webpage on your deafault browser,\n where you will be asked for permission to give access to application.\nClick \"Accept\" on GDrive webpage(you might have to log in first)");
Desktop.getDesktop().browse(java.net.URI.create(url));
String code = JOptionPane.showInputDialog(null, "Copy paste the code displayed on the webpage into this window");
//System.out.println(" " + url);
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
List<File> result = new ArrayList<File>();
result=retrieveAllFiles(service);
for(File f:result){
String ext = null;
System.out.println("File Name==>"+f.getTitle());
System.out.println("File Id==>"+f.getId());
System.out.println("File ext==>"+f.getFileExtension());
System.out.println("File size==>"+f.getFileSize());
InputStream in = downloadFile(service,f);
String fileType = f.getMimeType();
if(fileType.equals("text/plain"))
{
ext = ".txt";
}
byte b[] = new byte[in.available()];
in.read(b);
java.io.File ff = new java.io.File("C:\\GDrive_Download\\"+f.getTitle()+ ext);
FileOutputStream fout = new FileOutputStream(ff);
fout.write(b);
fout.close();
}
//Insert a file
// File body = new File();
// body.setTitle("RealtekLog");
// body.setDescription("A test document");
// body.setMimeType("text/plain");
//
//
//// downloadFile(service, body);
//
// java.io.File fileContent = new java.io.File("C:\\GDrive_Download\\My document.txt");
// FileContent mediaContent = new FileContent("text/plain", fileContent);
//
// File file = service.files().insert(body, mediaContent).execute();
// System.out.println("File ID: " + file.getId());
System.exit(0);
}
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
private static List<File> retrieveAllFiles(Drive service) throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
// ...
}
我也有上传代码,可以顺利运行。但下载让我很烦恼。所有专家都需要你的帮助。 GDrive上的txt文件具有以下数据
Hello world! this is the test for download done on GDrive , for the code written in java which will do the work of syncing the file to the cloud.
你好世界!这是在GDrive上完成的下载测试,用于用java编写的代码,用于将文件同步到云中。
你好世界!这是在GDrive上完成的下载测试,用于用java编写的代码,用于将文件同步到云中。
你好世界!这是在GDrive上完成的下载测试,用于用java编写的代码,用于将文件同步到云中。
下载的文件有以下数据
Hello world! this is the test
提前致谢&amp;圣诞快乐。
答案 0 :(得分:-1)
使用此代码
String filename = "C:\\folder name where you save file\\filename";
response.setContentType("application/octet-stream");
String disHeader = "Attachment; Filename=\"filename\"";
response.setHeader("Content-Disposition", disHeader);
File fileToDownload = new File(filename);
InputStream in = null;
ServletOutputStream outs = response.getOutputStream();
try {
in = new BufferedInputStream
(new FileInputStream(fileToDownload));
int ch;
while ((ch = in.read()) != -1) {
outs.print((char) ch);
}
}
finally {
if (in != null) in.close(); // very important
}
outs.flush();
outs.close();
in.close();