JAVA 使用 Google drive 的 API 服务
遵循Google develop操作指示 (英文指导DriveJava Quickstart)。可能用的人太少了,这个step写的和米共一样。可能是我看不懂en,也可能是我🧠不太好使。
- 首先需要去注册你的软件😄
-别问为什么这么麻烦,Google就是脸比较大,欠打。
-去这个网站 (注册和生成jsonOAuth client ID credentials)生成credentials.json文件。
-是desktop哦,记得不要选错。
-下载下来的json文件不叫这个名字?难道你不会自己改么? - 改build.gradle
记得改sourceCompatibility 和targetCompatibility1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17apply plugin: 'java'
apply plugin: 'application'
mainClassName = 'SheetsQuickstart'
sourceCompatibility = 11 //记得改这两个东西,你用哪个版本jdk就改成哪个版本的jdk
targetCompatibility = 11 //记得改这两个东西,你用哪个版本jdk就改成哪个版本的jdk
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.api-client:google-api-client:1.33.0'
implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1'
implementation 'com.google.apis:google-api-services-sheets:v4-rev20210629-1.32.1'
} - 接下来就可以获取drive的文件了
- 文件的ID就是你发文件网址的后面部分(看起来像hash code的那部分,不要带edit/啥啥啥的)
- 每次跳到网站要你同意使用google drive的权限都会生成一个token.如果你需要换账号则需要删除这个token.
- List
SCOPES改变的是使用drive的权限,下面代码的列子是权限最大的 - 第一个是生成drive service,其实就是建立TCP链接
- 第二个function是下载文件中的每个文件中的所有图片 (搜索文件的语法Search query terms and operators)
- 第三个function是上传文件
- 第四个function是删除文件夹中的所有文件
- 可能运行第一次会教你去注册google的api服务,说你的服务没有开启。反正报错会给你一个链接,自己点进去看就好了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import javafx.util.Pair;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.*;
/* class to demonstarte use of Drive files list API */
public class DriveQuickstart {
/** Application name. */
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
/** Directory to store authorization tokens for this application. */
private static final String TOKENS_DIRECTORY_PATH = "drivetokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private static Credential drive_token = null;
private static Drive service = null;
/**
* init the drive.
* @throws IOException If the credentials.json file cannot be found.
*/
public DriveQuickstart() throws IOException, GeneralSecurityException {
// Load client secrets.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
InputStream in = Main.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
//returns an authorized Credential object.
drive_token = credential;
service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static List<File> get_file() throws IOException, GeneralSecurityException {
//item-picture-upload
//mimeType != 'application/vnd.google-apps.folder'
// Print the names and IDs for all files.
FileList result = service.files().list()
.setQ("'11PJEUZl8QmZlNSl23_AfF3cjxKa-wgJH' in parents")
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
List<String> folderids = new ArrayList<>();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
folderids.add(file.getId());
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
List<File> imgs = new ArrayList<>();
if(folderids.size()!= 0){
for(String folderid : folderids){
FileList images = service.files().list()
.setQ( "'" + folderid+"'"+" in parents")
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> img_list = images.getFiles();
if (img_list == null || img_list.isEmpty()) {
System.out.println("No imgs found in folder: "+ folderid);
} else {
System.out.println(folderid+" imges num: "+ img_list.size());
imgs.addAll(img_list);
}
}
}
else{
System.out.println("no folders in this shared folder");
}
return imgs;
}
public void uploadBasic(List<Pair<String, File>> imgs, String realFolderId) throws IOException{
//clear this folder first
clear_folder("1RWaZWyCOABkoOUpZ2DJBBcGOrlBGv_lE");
Drive service = new Drive.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
drive_token)
.setApplicationName("Drive samples")
.build();
//create a new folder
File fileMetadata = new File();
fileMetadata.setName("image-output-0721-ShengWang");
fileMetadata.setParents(Collections.singletonList(realFolderId));
fileMetadata.setMimeType("application/vnd.google-apps.folder");
try {
File file = service.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("new folder id: "+file.getId());
//success create a folder then upload the image
//upload the paired images
for(Pair<String, File> img_pair : imgs){
File copy = new File();
copy.setParents(Collections.singletonList(file.getId()));
String out_name = img_pair.getKey()
.toLowerCase()
.replaceAll(" ", "-");
copy.setName(out_name);
try {
File resultFile = service.files().copy(img_pair.getValue().getId(), copy)
.setFields("id, parents")
.execute();
System.out.println(resultFile.getId());
}catch (GoogleJsonResponseException e) {
System.err.println("Unable to copy file: " + e.getDetails());
throw e;
}
}
System.out.printf("%d imgs uploaded\n", imgs.size());
//upload all used img
}catch (GoogleJsonResponseException e) {
System.err.println("Unable to create folder: " + e.getDetails());
throw e;
}
}
//clear the folder onclude the previous result
public void clear_folder(String folder_id) throws IOException {
List<String> ids = new ArrayList<>();
Drive service = new Drive.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
drive_token)
.setApplicationName("Drive samples")
.build();
//item-picture-upload
//mimeType != 'application/vnd.google-apps.folder'
// Print the names and IDs for all files.
FileList result = service.files().list()
.setQ("'"+folder_id+"'"+" in parents")
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("no previous result");
} else {
for (File file : files) {
ids.add(file.getId());
}
}
for(String id : ids){
try {
service.files().delete(id).execute();
System.out.println("delet previous folder: "+id);
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}
}
}