Manipulieren von Dateien und Ordnern auf Google Drive mithilfe von Java

View more Tutorials:

1- Das Zweck der Unterricht

Sehen Sie mehr
In dieser Unterricht leite ich Sie durch  Google Drive Java API die Manipulation mit Google Drive an. Die Themen, die in dieser Unterricht diskutiert werden, fasst um:
  1. Eine Applikation Java erstellen und die Bibliothek anmelden um Google Drive API zu verwenden.
  2. Credentials erstellen um mit Google Drive manipulieren zu können.
  3. Mit der File und Verzeichnis auf Google Drive durch Google Drive API ​​​​​​​manipulieren.

2-  Credentials erstellen

Angenommen, Sie haben ein  Gmail Konto   [email protected], dann bietet  Google die umsonste Festplatteskapazität von  15GB in  Google Drive an, darauf können Sie Ihre File lagern. Damit Ihre Applikation mit der File auf Google Drive manipulieren kann, braucht sie ein  Credentials . Credentials ist einfach eine File, die auf dem Computer, wo Ihre Applikation implementiert wird, gestellt wird. Wie die folgende Illustration:

Um eine obengemeinte  Credentials zu haben, brauchen Sie ein Projekt auf  Google Developer Console erstellen und die File    client_secret.json herunterladen.

3- Java Google Drive API

Mit der  Maven benutzenden Projekte brauchen Sie die folgenden Abhängigkeiten (dependencies) anmelden:
<!-- 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- Mit einen Beispiel schnell starten

Ein Projekt  Maven und die Klasse  DriveQuickstart erstellen um mit  Google Drive API schnell zu starten.
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());
            }
        }
    }
}
Bei dem ersten Mal zum Schnellen der Klasse DriveQuickstart wird ein Verzeichnis  {user_home}/credentials erstellt wenn er existiert nicht.
Windows C:\Users\{user}\credentials
Linux /home/{user}/credentials
Stellen Sie sicher, dass Sie eine File  client_secret.json hatte, umsonst lesen Sie die folgende Anleitung:
Die File  client_secret.json in den obengemeinte Verzeichnis kopieren:
Die Klasse  DriveQuickstart noch ein Mal laufen. Aufs Fenster  Console kopieren Sie die Link und auf dem Browser es zugreifen.
Bei dem Zugang zur Link auf dem Browser wird es darauf fordern, dass Sie mit einem Konto  Gmail anmelden. Jetzt brauchen Sie mit dem Konto  Gmail anmelden, wo Sie die File client_secret.json erstellt haben.
Jetzt wird eine File mit dem Name von  StoredCredential auf dem Verzeichnis   {user_home}/credential erstellt werden.
Credential wurde auf der Festplatte Ihres Computer gelagert. Ab jetzt brauchen Sie beim Arbeiten mit  Google Drive diese Schritten wie oben nicht durchgehen.
Die Klasse  DriveQuickstart noch einmal laufen und das Ergebnis aufs Fenster  Console sehen. Das Programm wird die Liste der Files und Verzeichnisse auf Ihr  Google Drive ausdrucken.

5- Die Struktur von File und Directory vom Google Drive

Die Definition vom Verzeichnis (Directory) und File im  Google Drive sind ziemlich unterschiedlich von der Definition von  Directory & File auf dem Betriebssytem. Dann sind das die grundlegendlichen Eigenschaften:
  1. Im Google Drive kann ein File/Directory einen oder vielen Vater-Directory .
  2. In einen gleichen Directory haben die File können den gleichen Name aber die unterschiedlichen ID haben.
  3. Die Klasse com.google.api.services.drive.model.File vertritt die beiden File und Directory.
Die Klasse  com.google.api.services.drive.model.File hat vielen Felder (field) wie die folgende Illustration:
Es gibt 2 wichtigen Felder (field). Das sind  mineType & parents:

parents

Die  ID Liste der Vater-Verzeichnisse von den momentanen File (Verzeichnis) tại. Die Hauptverzeichnis (root) oder Hauptfile hat den Vaterverzeichnis mit  ID = "root".

mineType

MIME Type Description
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
.....  
Die Operators, die für die Felder benutzt werden (field):
Field Value Type Operators Description
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- Die Klasse 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

Wenn Sie  ID eines Verzeichnis (Directory) kennen, können Sie die Liste der Sub-Verzeichnisse dieses Verzeichnis aufnehmen. Achten Sie darauf, in  Google Drive kann eine File oder ein Verzeichnis einen oder vielen Vater-Verzeichnis
Jetzt sehen Sie das Beispiel: die Sub-Verzeichnis eines Verzeichnis herausholen und das Beispiel vom Herausholen der Liste der Hauptverzeichnisse
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());
        }
    }

}
Achtung: Sie haben ein Objekt  com.google.api.services.drive.model.File, aber nicht alle Felder (field) von ihm werden die Wert angewiesen. Nur die Fälle, für den Sie sich interessiert sind, werden die Wert angewiesen, umgekehrt hat es die Wert  null.
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();
Ein nächstes Beispiel: die Verzeichnisse nach dem Name suchen, die ein Sub-Verzeichnis eines Verzeichnis ist.
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

Um auf  Google Drive die File zu suchen, sollen Sie die Abfragenbedingungen wie folgend verwenden:
  • 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- Das Verzeichnis auf Google Drive erstellen

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- Die File auf Google Drive erstellen

Es gibt 3 üblichen Wege, damit Sie eine File auf   Google Driver erstellen können:
    1. Upload File
    2. byte[]
    3. 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- Google File/Folder teilen

    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 = "[email protected]";
    
            // Share for a User
            createPermissionForEmail(googleFileId1, googleEmail);
    
            String googleFileId2 = "some-google-file-id-2";
    
            // Share for everyone
            createPublicPermission(googleFileId2);
    
            System.out.println("Done!");
        }
    
    }
    

    View more Tutorials: