0% found this document useful (0 votes)
3 views7 pages

Java Google Drive Operations Guide

The Java program demonstrates various operations on Google Drive, including listing files, searching for specific files, and managing folders. Key functionalities include creating new folders, uploading files, and listing both root and subdirectories. The program utilizes Google Drive API for authentication and file management tasks.

Uploaded by

Mariya Hodekar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Java Google Drive Operations Guide

The Java program demonstrates various operations on Google Drive, including listing files, searching for specific files, and managing folders. Key functionalities include creating new folders, uploading files, and listing both root and subdirectories. The program utilizes Google Drive API for authentication and file management tasks.

Uploaded by

Mariya Hodekar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1.

Write a Java Program to perform following operations on googleDrive:

a. Listing first two files in google drive

b. Searching file on google drive

c. List all folders under root directory in google drive

d. List subdirectories under specific folder

e. Creating new folder

f. Upload file in newly created folder

Program:

package gdriveDemo;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

public class GDrive_Demo {

private static final JsonFactory JSON_FACTORY=[Link]();

//Directory to store user credentials for this application

private static final [Link] CREDENTIALS_FOLDER=new [Link]("C:\\DSCC_Credentials");

private static final List<String> SCOPES=[Link]([Link]);

//-----------------AUTHENTICATION----------------------------------

private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)throws


IOException{

[Link] clientSecretFilePath=new
[Link]("C:\\DSCC_Credentials\\client_secret.json");

if (![Link]()) {

throw new FileNotFoundException("Credentials File not found...");

try(InputStream in = new FileInputStream(clientSecretFilePath)){

GoogleClientSecrets clientSecrets=[Link](JSON_FACTORY,new
InputStreamReader(in));

GoogleAuthorizationCodeFlow flow=new [Link](

HTTP_TRANSPORT,JSON_FACTORY,clientSecrets,SCOPES)

.setDataStoreFactory(new
FileDataStoreFactory(CREDENTIALS_FOLDER))

.setAccessType("offline")

.build();

return new AuthorizationCodeInstalledApp(flow,new


LocalServerReceiver()).authorize("user");

//-----------------FILE LISTING----------------------------------

private static void listFiles(Drive service, int pageSize) throws IOException {


FileList result = [Link]().list()

.setPageSize(pageSize)

.setFields("nextPageToken, files(id, name)")

.execute();

List<File> files = [Link]();

if (files == null || [Link]()) {

[Link]("No files found.");

} else {

[Link]("Files:");

for (File file : files) {

[Link]("%s (%s)%n", [Link](), [Link]());

//-----------------FILE SEARCH----------------------------------

private static void searchFiles(Drive service, String query) throws IOException {

String pageToken = null;

int srNo = 1;

boolean found = false;

[Link]("Search Results:");

do {

FileList result = [Link]().list()

.setQ(query)

.setSpaces("drive")

.setFields("nextPageToken, files(id, name, createdTime, mimeType)")

.setPageToken(pageToken)

.execute();

for (File file : [Link]()) {

found = true;

[Link](srNo++ + ". " + [Link]() + "\t" + [Link]());

}
pageToken = [Link]();

} while (pageToken != null);

if (!found) {[Link]("No files found for query: " + query);}

//-----------------LIST ROOT FOLDERS----------------------------------

private static List<File> listRootFolders(Drive service) throws IOException {

String query = "mimeType = 'application/[Link]' and 'root' in parents";

FileList result = [Link]().list()

.setQ(query)

.setSpaces("drive")

.setFields("files(id, name)")

.execute();

List<File> folders = [Link]();

int srNo = 0;

[Link]("Root Folders:");

for (File folder : folders) {

[Link](srNo++ + ". " + [Link]() + "\t" + [Link]());

return folders;

//-----------------LIST SUBFOLDERS----------------------------------

private static void listSubFolders(Drive service, String parentFolderId) throws IOException {

String query = "mimeType = 'application/[Link]' and '" + parentFolderId + "' in


parents";

FileList result = [Link]().list()

.setQ(query)

.setSpaces("drive")

.setFields("files(id, name)")

.execute();

int srNo = 0;

[Link]("SubFolders:");
for (File subFolder : [Link]()) {

[Link](srNo++ + ". " + [Link]() + "\t" + [Link]());

//-----------------CREATE FOLDER----------------------------------

private static File createFolder(Drive service,String folderName,String parentFolderId )throws


IOException{

File folderMetadata=new File();

[Link](folderName);

[Link]("application/[Link]");

if(parentFolderId!= null) {

[Link]([Link](parentFolderId));

File createdFolder=[Link]().create(folderMetadata)

.setFields("id,name,parents")

.execute();

[Link]("Folder Created: "+[Link]()+" under dir


"+[Link]()+

"(ID: "+[Link]()+")");

return createdFolder;

// --------------------- UPLOAD FILE ---------------------

private static File uploadFile(Drive service, String localFilePath, String mimeType,

String uploadFileName, String parentFolderId) throws IOException {

[Link] localFile = new [Link](localFilePath);

try (FileInputStream fis = new FileInputStream(localFile)) {

AbstractInputStreamContent uploadStreamContent = new InputStreamContent(mimeType, fis);

File fileMetadata = new File();

[Link](uploadFileName);

if (parentFolderId != null) {

[Link]([Link](parentFolderId));
}

File uploadedFile = [Link]()

.create(fileMetadata, uploadStreamContent)

.setFields("id, name, webContentLink, webViewLink, parents")

.execute();

[Link]("File Uploaded: " + [Link]());

[Link]("WebContentLink: " + [Link]());

[Link]("WebViewLink: " + [Link]());

return uploadedFile;

// --------------------- MAIN ---------------------

public static void main(String[] args) throws IOException, GeneralSecurityException {

final NetHttpTransport HTTP_TRANSPORT = [Link]();

Credential credential = getCredentials(HTTP_TRANSPORT);

Drive service = new [Link](HTTP_TRANSPORT, JSON_FACTORY, credential)

.setApplicationName("GDrive Access")

.build();

[Link]("----" + [Link]() + "----");

// 1. List first 2 files

listFiles(service, 2);

// 2. Search files

searchFiles(service, "name contains 'MyGDriveJavaFile'");

// 3. Show root folders & pick one

List<File> rootFolders = listRootFolders(service);

Scanner input = new Scanner([Link]);

[Link]("Enter serial number of folder to see subfolders:");

int choice = [Link]();

String parentFolderId = [Link](choice).getId();

// 4. List subfolders of chosen folder

listSubFolders(service, parentFolderId);
// 5. Create new folder under root

File newFolder = createFolder(service, "FolderUsingJava", null);

// 6. Upload file inside new folder

uploadFile(service,

"E:\\Sem_3\\DSCC\\practical_5_files\\[Link]",

"application/[Link]",

"[Link]",

[Link]());

Output:

You might also like