Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading directly from Google Drive in Java

Please I need to read the content of a file stored in Google Drive programmatically. I'm looking forward to some sort of
InputStream is = <drive_stuff>.read(fileID);
Any help? I'll also appreciate if I can write back to a file using some sort of

OutputStream dos = new DriveOutputStream(driveFileID);
dos.write(data);

If this sort of convenient approach is too much for what Drive can offer, please I'll like to have suggestions on how I can read/write to Drive directly from java.io.InputStream / OutputStream / Reader / Writer without creating temporary local file copies of the data I want to ship to drive. Thanks!

like image 365
Sayo Oladeji Avatar asked Dec 04 '25 17:12

Sayo Oladeji


1 Answers

// Build a new authorized API client service. Drive service = getDriveService();

    // 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.size() == 0) {
        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());
            String fileId = file.getId();

                Export s=service.files().export(fileId, "text/plain");
                InputStream in=s.executeMediaAsInputStream();
                InputStreamReader isr=new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
                String line = null;

                StringBuilder responseData = new StringBuilder();
                while((line = br.readLine()) != null) {
                    responseData.append(line);
                }
                System.out.println(responseData);
            } 
        }
    }
like image 130
V.Barod Avatar answered Dec 06 '25 08:12

V.Barod