Manipulation de fichiers et de dossiers sur Google Drive à l'aide de Java
1. Objectif de la leçon
Voir plus :
Dans cette leçon, je vous donnerai des instructions de la manipulation avec Google Drive via Google Drive Java API. Des sujets discutés dans cette leçon comprennent :
- Créer une application Java et déclarer des bibliothèques pour utiliser le Google Drive API.
- Créer un certificat (Credentials) pour intéagir avec Google Drive.
- Manipuler des fichiers ainsi que des dossiers sur Google Drive via Google Drive API.
2. Créer Credentials
Supposons que vous ayez un compte Gmail : abc@gmail.com, Google vous fournira gratuitement 15 Go d'espace disque sur Google Drive. Vous pouvez y stocker vos fichiers. Pour que votre application puisse manipuler les fichiers sur Google Drive, elle doit disposer d'un Credentials. Les informations d'identification sont simplement un fichier qui sera placé sur l'ordinateur sur lequel votre application est déployée, comme illustré ci-dessous:
Pour obtenir Credentials (Accrédition) mentionné ci-dessous, vous devez créer un projet sur Google Developer Console, et le télécharger dans le fichier client_secret.json.
3. Java Google Drive API
Pour les projets utilisant Maven, vous avez besoin de déclarer les dépendances (dependencies) ci-dessous :
<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-drive -->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-drive</artifactId>
<version>v3-rev105-1.23.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.23.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.23.0</version>
</dependency>
4. Démarrer rapidement avec un exemple
Créez un projet Maven, et créez la classe DriveQuickstart pour commencer rapidement avec Google Drive API.
DriveQuickstart.java
package org.o7planning.googledrive.quickstart;
import 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.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
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 java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class DriveQuickstart {
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
// Directory to store user credentials for this application.
private static final java.io.File CREDENTIALS_FOLDER //
= new java.io.File(System.getProperty("user.home"), "credentials");
private static final String CLIENT_SECRET_FILE_NAME = "client_secret.json";
//
// Global instance of the scopes required by this quickstart. If modifying these
// scopes, delete your previously saved credentials/ folder.
//
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
if (!clientSecretFilePath.exists()) {
throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
+ " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
}
// Load client secrets.
InputStream in = new FileInputStream(clientSecretFilePath);
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(CREDENTIALS_FOLDER))
.setAccessType("offline").build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
System.out.println("CREDENTIALS_FOLDER: " + CREDENTIALS_FOLDER.getAbsolutePath());
// 1: Create CREDENTIALS_FOLDER
if (!CREDENTIALS_FOLDER.exists()) {
CREDENTIALS_FOLDER.mkdirs();
System.out.println("Created Folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
System.out.println("Copy file " + CLIENT_SECRET_FILE_NAME + " into folder above.. and rerun this class!!");
return;
}
// 2: Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
// 3: Read client_secret.json file & create Credential object.
Credential credential = getCredentials(HTTP_TRANSPORT);
// 5: Create Google Drive Service.
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
.setApplicationName(APPLICATION_NAME).build();
// Print the names and IDs for up to 10 files.
FileList result = service.files().list().setPageSize(10).setFields("nextPageToken, files(id, name)").execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
Pour la première fois, exécutez la classe DriveQuickstart, un dossier {user_home}/credentials sera créé s'il n'existe pas encore.
Windows | C:\Users\{user}\credentials |
Linux | /home/{user}/credentials |
Assurez- vous que vous avez obtenu le fichier client_secret.json, si non, observez les instructions ci-dessous :
Copiez le fichier client_secret.json au dossier mentionné ci-dessus :
Exécutez la classe DriveQuickstart une autre fois. Sur la fenêtre Console copiez le lien et l'accédez sur le navigateur.
Lorsque vous accédez au lien (Link) sur le navigateur, il vous demandera de se connecter avec un compte de Gmail. En ce moment, vous devez vous connecter avec le compte de Gmail que vous avez créé dans le fichier client_secret.json.
En ce moment, un fichier nommé StoredCredential sera créé sur le dossier {user_home}/credential.
Le Credential (Accrédition) a été stocké sur le disque dur de votre ordinateur. À partir de maintenant, lorsque vous travaillez avec Google Drive ce n'est pas la pein de passer les étapes précédentes.
Exécutez la classe DriveQuickstart encore une autre fois, et observez le résultat recu sur la fenêtre de Console. Le programme imprimera la liste des fichiers et des dossiers sur votre Google Drive.
5. Structure File et Directory de Google Drive
La définition du dossier (Directory) et du fichier (File) sur Google Drive est un peu différent avec celle de Directory & File sur des systèmes d'exploitation. Voici des différence à la base :
- Sur Google Drive un File/Directory peut avoir un ou plusieurs Directory parents.
- Dans un dossier, des fichiers peut obtenir le même nom, mais ID différent.
- La classe com.google.api.services.drive.model.File se représente tous les deux, File et Directory.
La classe com.google.api.services.drive.model.File a plusieurs champs (field) comme l'illustration ci-dessous :
Il y a deux champs (field) importants qui sont mineType & parents :
parents
La liste ID des dossiers parents des fichiers actuels. Les répertoires racines (root) ou des fichiers racines obtiennent le dossier parent avec ID = "root".
mineType
application/vnd.google-apps.audio | |
application/vnd.google-apps.document | Google Docs |
application/vnd.google-apps.drawing | Google Drawing |
application/vnd.google-apps.file | Google Drive file |
application/vnd.google-apps.folder | Google Drive folder |
application/vnd.google-apps.form | Google Forms |
application/vnd.google-apps.fusiontable | Google Fusion Tables |
application/vnd.google-apps.map | Google My Maps |
application/vnd.google-apps.photo | |
application/vnd.google-apps.presentation | Google Slides |
application/vnd.google-apps.script | Google Apps Scripts |
application/vnd.google-apps.site | Google Sites |
application/vnd.google-apps.spreadsheet | Google Sheets |
application/vnd.google-apps.unknown | |
application/vnd.google-apps.video | |
application/vnd.google-apps.drive-sdk | 3rd party shortcut |
..... |
Des opérateurs ont été utilisés pour des champs (field) :
name | string | contains, =, != | Name of the file. |
fullText | string | contains | Full text of the file including name, description, content, and indexable text. |
mimeType | string | contains, =, != | MIME type of the file. |
modifiedTime | date | <=, <, =, !=, >, >= | Date of the last modification of the file. |
viewedByMeTime | date | <=, <, =, !=, >, >= | Date that the user last viewed a file. |
trashed | boolean | =, != | Whether the file is in the trash or not. |
starred | boolean | =, != | Whether the file is starred or not. |
parents | collection | in | Whether the parents collection contains the specified ID. |
owners | collection | in | Users who own the file. |
writers | collection | in | Users or groups who have permission to modify the file. |
readers | collection | in | Users or groups who have permission to read the file. |
sharedWithMe | boolean | =, != | Files that are in the user's "Shared with me" collection. |
properties | collection | has | Public custom file properties. |
appProperties | collection | has | Private custom file properties. |
visibility | string | =, '!=' | The visibility level of the file. Valid values are anyoneCanFind, anyoneWithLink, domainCanFind, domainWithLink, and limited. |
6. La classe GoogleDriveUtils
GoogleDriveUtils.java
package org.o7planning.googledrive.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
import 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.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
public class GoogleDriveUtils {
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
// Directory to store user credentials for this application.
private static final java.io.File CREDENTIALS_FOLDER //
= new java.io.File(System.getProperty("user.home"), "credentials");
private static final String CLIENT_SECRET_FILE_NAME = "client_secret.json";
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
// Global instance of the {@link FileDataStoreFactory}.
private static FileDataStoreFactory DATA_STORE_FACTORY;
// Global instance of the HTTP transport.
private static HttpTransport HTTP_TRANSPORT;
private static Drive _driveService;
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(CREDENTIALS_FOLDER);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
public static Credential getCredentials() throws IOException {
java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
if (!clientSecretFilePath.exists()) {
throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
+ " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
}
InputStream in = new FileInputStream(clientSecretFilePath);
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(DATA_STORE_FACTORY).setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
public static Drive getDriveService() throws IOException {
if (_driveService != null) {
return _driveService;
}
Credential credential = getCredentials();
//
_driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
.setApplicationName(APPLICATION_NAME).build();
return _driveService;
}
}
7. SubFolder & RootFolder
Si vous save le ID d'un dossier (Directory) vous pouvez prendre la liste des sous dossiers dans ce dossier parent. Il est à noter que dans Google Drive un fichier (ou un dossier) peut contenir un ou plusieurs dossiers parents.
Maintenant, prennez l'exemple de la liste des sous dossiers dans un dossier parent et l'exemple de l'extrait la liste des dossiers parents.
GetSubFolders.java
package org.o7planning.googledrive.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.o7planning.googledrive.utils.GoogleDriveUtils;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class GetSubFolders {
// com.google.api.services.drive.model.File
public static final List<File> getGoogleSubFolders(String googleFolderIdParent) throws IOException {
Drive driveService = GoogleDriveUtils.getDriveService();
String pageToken = null;
List<File> list = new ArrayList<File>();
String query = null;
if (googleFolderIdParent == null) {
query = " mimeType = 'application/vnd.google-apps.folder' " //
+ " and 'root' in parents";
} else {
query = " mimeType = 'application/vnd.google-apps.folder' " //
+ " and '" + googleFolderIdParent + "' in parents";
}
do {
FileList result = driveService.files().list().setQ(query).setSpaces("drive") //
// Fields will be assigned values: id, name, createdTime
.setFields("nextPageToken, files(id, name, createdTime)")//
.setPageToken(pageToken).execute();
for (File file : result.getFiles()) {
list.add(file);
}
pageToken = result.getNextPageToken();
} while (pageToken != null);
//
return list;
}
// com.google.api.services.drive.model.File
public static final List<File> getGoogleRootFolders() throws IOException {
return getGoogleSubFolders(null);
}
public static void main(String[] args) throws IOException {
List<File> googleRootFolders = getGoogleRootFolders();
for (File folder : googleRootFolders) {
System.out.println("Folder ID: " + folder.getId() + " --- Name: " + folder.getName());
}
}
}
Remarque : Vous avez un objet com.google.api.services.drive.model.File, mais tous ses champs (field) ne sont pas associés à des valeurs. Seuls les cas qui vous intéressent sont des valeurs attribuées. Au contraire, il a une valeur nulle.FileList result = driveService.files().list().setQ(query).setSpaces("drive") // // Fields will be assigned values: id, name, createdTime .setFields("nextPageToken, files(id, name, createdTime)")// .setPageToken(pageToken).execute();
L'exemple suivante : cherchez des dossiers par le nom qui sont des sous dossier d'un dossier parent.
GetSubFoldersByName.java
package org.o7planning.googledrive.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.o7planning.googledrive.utils.GoogleDriveUtils;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class GetSubFoldersByName {
// com.google.api.services.drive.model.File
public static final List<File> getGoogleSubFolderByName(String googleFolderIdParent, String subFolderName)
throws IOException {
Drive driveService = GoogleDriveUtils.getDriveService();
String pageToken = null;
List<File> list = new ArrayList<File>();
String query = null;
if (googleFolderIdParent == null) {
query = " name = '" + subFolderName + "' " //
+ " and mimeType = 'application/vnd.google-apps.folder' " //
+ " and 'root' in parents";
} else {
query = " name = '" + subFolderName + "' " //
+ " and mimeType = 'application/vnd.google-apps.folder' " //
+ " and '" + googleFolderIdParent + "' in parents";
}
do {
FileList result = driveService.files().list().setQ(query).setSpaces("drive") //
.setFields("nextPageToken, files(id, name, createdTime)")//
.setPageToken(pageToken).execute();
for (File file : result.getFiles()) {
list.add(file);
}
pageToken = result.getNextPageToken();
} while (pageToken != null);
//
return list;
}
// com.google.api.services.drive.model.File
public static final List<File> getGoogleRootFoldersByName(String subFolderName) throws IOException {
return getGoogleSubFolderByName(null,subFolderName);
}
public static void main(String[] args) throws IOException {
List<File> rootGoogleFolders = getGoogleRootFoldersByName("TEST");
for (File folder : rootGoogleFolders) {
System.out.println("Folder ID: " + folder.getId() + " --- Name: " + folder.getName());
}
}
}
8. Search Files
Afin de chercher des fichiers sur Google Drive, vous devriez utiliser la condition de requête ci-dessous :
- mimeType != 'application/vnd.google-apps.folder'
FindFilesByName.java
package org.o7planning.googledrive.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.o7planning.googledrive.utils.GoogleDriveUtils;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class FindFilesByName {
// com.google.api.services.drive.model.File
public static final List<File> getGoogleFilesByName(String fileNameLike) throws IOException {
Drive driveService = GoogleDriveUtils.getDriveService();
String pageToken = null;
List<File> list = new ArrayList<File>();
String query = " name contains '" + fileNameLike + "' " //
+ " and mimeType != 'application/vnd.google-apps.folder' ";
do {
FileList result = driveService.files().list().setQ(query).setSpaces("drive") //
// Fields will be assigned values: id, name, createdTime, mimeType
.setFields("nextPageToken, files(id, name, createdTime, mimeType)")//
.setPageToken(pageToken).execute();
for (File file : result.getFiles()) {
list.add(file);
}
pageToken = result.getNextPageToken();
} while (pageToken != null);
//
return list;
}
public static void main(String[] args) throws IOException {
List<File> rootGoogleFolders = getGoogleFilesByName("u");
for (File folder : rootGoogleFolders) {
System.out.println("Mime Type: " + folder.getMimeType() + " --- Name: " + folder.getName());
}
System.out.println("Done!");
}
}
9. Créer un dossier sur Google Drive
CreateFolder.java
package org.o7planning.googledrive.example;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.o7planning.googledrive.utils.GoogleDriveUtils;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
public class CreateFolder {
public static final File createGoogleFolder(String folderIdParent, String folderName) throws IOException {
File fileMetadata = new File();
fileMetadata.setName(folderName);
fileMetadata.setMimeType("application/vnd.google-apps.folder");
if (folderIdParent != null) {
List<String> parents = Arrays.asList(folderIdParent);
fileMetadata.setParents(parents);
}
Drive driveService = GoogleDriveUtils.getDriveService();
// Create a Folder.
// Returns File object with id & name fields will be assigned values
File file = driveService.files().create(fileMetadata).setFields("id, name").execute();
return file;
}
public static void main(String[] args) throws IOException {
// Create a Root Folder
File folder = createGoogleFolder(null, "TEST-FOLDER");
System.out.println("Created folder with id= "+ folder.getId());
System.out.println(" name= "+ folder.getName());
System.out.println("Done!");
}
}
10. Créer un fichier sur Google Drive
Il y a trois moyens communs pour que vous puissiez créer un fichier sur Google Driver :
- Upload File
- byte[]
- InputStream
CreateGoogleFile.java
package org.o7planning.googledrive.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import org.o7planning.googledrive.utils.GoogleDriveUtils;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
public class CreateGoogleFile {
// PRIVATE!
private static File _createGoogleFile(String googleFolderIdParent, String contentType, //
String customFileName, AbstractInputStreamContent uploadStreamContent) throws IOException {
File fileMetadata = new File();
fileMetadata.setName(customFileName);
List<String> parents = Arrays.asList(googleFolderIdParent);
fileMetadata.setParents(parents);
//
Drive driveService = GoogleDriveUtils.getDriveService();
File file = driveService.files().create(fileMetadata, uploadStreamContent)
.setFields("id, webContentLink, webViewLink, parents").execute();
return file;
}
// Create Google File from byte[]
public static File createGoogleFile(String googleFolderIdParent, String contentType, //
String customFileName, byte[] uploadData) throws IOException {
//
AbstractInputStreamContent uploadStreamContent = new ByteArrayContent(contentType, uploadData);
//
return _createGoogleFile(googleFolderIdParent, contentType, customFileName, uploadStreamContent);
}
// Create Google File from java.io.File
public static File createGoogleFile(String googleFolderIdParent, String contentType, //
String customFileName, java.io.File uploadFile) throws IOException {
//
AbstractInputStreamContent uploadStreamContent = new FileContent(contentType, uploadFile);
//
return _createGoogleFile(googleFolderIdParent, contentType, customFileName, uploadStreamContent);
}
// Create Google File from InputStream
public static File createGoogleFile(String googleFolderIdParent, String contentType, //
String customFileName, InputStream inputStream) throws IOException {
//
AbstractInputStreamContent uploadStreamContent = new InputStreamContent(contentType, inputStream);
//
return _createGoogleFile(googleFolderIdParent, contentType, customFileName, uploadStreamContent);
}
public static void main(String[] args) throws IOException {
java.io.File uploadFile = new java.io.File("/home/tran/Downloads/test.txt");
// Create Google File:
File googleFile = createGoogleFile(null, "text/plain", "newfile.txt", uploadFile);
System.out.println("Created Google file!");
System.out.println("WebContentLink: " + googleFile.getWebContentLink() );
System.out.println("WebViewLink: " + googleFile.getWebViewLink() );
System.out.println("Done!");
}
}
11. Partager Google File/ Folder
ShareGoogleFile.java
package org.o7planning.googledrive.example;
import java.io.IOException;
import org.o7planning.googledrive.utils.GoogleDriveUtils;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.Permission;
public class ShareGoogleFile {
// Public a Google File/Folder.
public static Permission createPublicPermission(String googleFileId) throws IOException {
// All values: user - group - domain - anyone
String permissionType = "anyone";
// All values: organizer - owner - writer - commenter - reader
String permissionRole = "reader";
Permission newPermission = new Permission();
newPermission.setType(permissionType);
newPermission.setRole(permissionRole);
Drive driveService = GoogleDriveUtils.getDriveService();
return driveService.permissions().create(googleFileId, newPermission).execute();
}
public static Permission createPermissionForEmail(String googleFileId, String googleEmail) throws IOException {
// All values: user - group - domain - anyone
String permissionType = "user"; // Valid: user, group
// organizer - owner - writer - commenter - reader
String permissionRole = "reader";
Permission newPermission = new Permission();
newPermission.setType(permissionType);
newPermission.setRole(permissionRole);
newPermission.setEmailAddress(googleEmail);
Drive driveService = GoogleDriveUtils.getDriveService();
return driveService.permissions().create(googleFileId, newPermission).execute();
}
public static void main(String[] args) throws IOException {
String googleFileId1 = "some-google-file-id-1";
String googleEmail = "test.o7planning@gmail.com";
// Share for a User
createPermissionForEmail(googleFileId1, googleEmail);
String googleFileId2 = "some-google-file-id-2";
// Share for everyone
createPublicPermission(googleFileId2);
System.out.println("Done!");
}
}
Tutoriels Java Open Source Libraries
- Le Tutoriel de Java JSON Processing API (JSONP)
- Utilisation de l'API Java Scribe OAuth avec Google OAuth2
- Obtenir des informations sur le matériel dans l'application Java
- Restfb Java API pour Facebook
- Créer Credentials pour Google Drive API
- Le Tutoriel de Java JDOM2
- Le Tutoriel de Java XStream
- Utiliser Java Jsoup pour analyser HTML
- Récupérer des informations géographiques basées sur l'adresse IP à l'aide de GeoIP2 Java API
- Lire et écrire un fichier Excel en Java à l'aide d'Apache POI
- Explorer le Facebook Graph API
- Manipulation de fichiers et de dossiers sur Google Drive à l'aide de Java
Show More