Is there any possible way to read the text from a file on Google Drive and store it in a String? This file may contain images as well. I was looking into the Google Drive SDK but they only allow us to download the entire file. How should I go about doing this?
From Files.get() documentation.
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
You can convert InputStream to String or File as you want.
Related
How to get media files and their details with Dropbox API v2 for Android(Java)? I have gone through the documentation for the FileMetadata , but I couldn't find the methods to get file details like file type(e.g. music, video, photo, text, ...) , file's URL and thumbnail.
this is my folders and files list Asyntask:
//login
DbxClientV2 client = DropboxClient.getClient(accessToken);
// Get files and folder metadata from root directory
String path = "";
TreeMap<String, Metadata> children = new TreeMap<>();
try {
try {
result = client.files().listFolder(path);
arrayList = new ArrayList<>();
//arrayList.add("/");
while (true) {
int i = 0;
for (Metadata md : result.getEntries()) {
if (md instanceof DeletedMetadata) {
children.remove(md.getPathLower());
} else {
String fileOrFolder = md.getPathLower();
children.put(fileOrFolder, md);
//if (!fileOrFolder.contains("."))//is a file
arrayList.add(fileOrFolder);
if (md instanceof FileMetadata) {
FileMetadata file = (FileMetadata) md;
//I need something like file.mineType, file.url, file.thumbnail
file.getParentSharedFolderId();
file.getName();
file.getPathLower();
file.getPathDisplay();
file.getClientModified();
file.getServerModified();
file.getSize();//in bytes
MediaInfo mInfo = file.getMediaInfo();//Additional information if the file is a photo or video, null if not present
MediaInfo.Tag tag;
if (mInfo != null) {
tag = mInfo.tag();}
}
}
i++;
}
if (!result.getHasMore()) break;
try {
result = client.files().listFolderContinue(result.getCursor());//what is this for ?
} catch (ListFolderContinueErrorException ex) {
ex.printStackTrace();
}
}
} catch (ListFolderErrorException ex) {
ex.printStackTrace();
}
} catch (DbxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
If you want media information, you should use listFolderBuilder to get a ListFolderBuilder object. You can use call .withIncludeMediaInfo(true) to set the parameter for media information, and then .start() to make the API call. The results will then have the media information set, where available.
Dropbox API v2 doesn't offer mime types, but you can keep your own file extension to mime type mapping as desired.
To get an existing link for a file, use listSharedLinks. To create a new one, use createSharedLinkWithSettings.
To get a thumbnail for a file, use getThumbnail.
i want to create a comic reader project on android. In my database, i only save path to the chapter directory which was taken from folderID on google drive. When user request to read comic, i want to through google client api to browse folder and get all file inside it.
i've seen guilde on https://developers.google.com/drive/v2/reference/files/list
but i still do not understand how it works, specials parameter Drive, how can i get it?
Thanks for any supports.
private static List<File> retrieveAllFiles(Drive service) throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
I have the following code for getting DriveContents of a file in Google Drive. I'm able to import and get DriveContents of MS Word, text files, etc but when the file is native to Google (Google Doc, Google Sheets, etc.) i'm not able to get the contents. My code is below:
selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
public void onResult(DriveApi.DriveContentsResult result) {
try {
if (!result.getStatus().isSuccess()) {
// display an error saying file can't be opened
Log.e(TAG, "Could not get file contents");
return;
}
// DriveContents object contains pointers
// to the actual byte stream
DriveContents contents = result.getDriveContents();
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
String contentsAsString = builder.toString();
contents.discard(getGoogleApiClient());
Log.i(TAG, contentsAsString);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Whenever I get a Google format file, it simply returns a result that is not a success and shows the error in my logs. How can I get the file contents of those files as well? Is there something special i'm supposed to do?
I'm reading the following documentation:
https://developers.google.com/drive/android/files
Not sure if this is the best solution but I did it the following way. I check in the metadata if it's a Google format (doc, sheets, etc) and if it is, I have an AsyncTask that does the below:
// accountName is the email address the user used when choosing which account
String scope = "oauth2:https://www.googleapis.com/auth/drive.file";
token = GoogleAuthUtil.getTokenWithNotification(fragment.getActivity(), accountName, scope, null);
After doing the above, you can get the file using the API:
https://developers.google.com/drive/web/manage-downloads
The token from the above gives the Authentication header token on the downloading. We can export the file as docx, pdf, etc and download it that way.
I can download the original file from Google Drive by using the following code :
public static InputStream downloadFile(Drive service, File file)
throws IOException {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp = service.getRequestFactory()
.buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
But it looks like the connection really low when downloading many files to add into the grid view.
Therefore, I need to list thumb nail instead of original file as it will be better for the connection.
Please help me how?
Use File.getThumbnail method to get the thumbnail or File.getIconLink to get the icon link.
This is a follow-up of this question. I have written my data file on Drive application folder, now the same app that created these files needs to retrieve them.
This doesn't work (I get the listing of the file, but the request of file download return with a 401 error):
private ArrayList<File> listFilesInApplicationDataFolder(Drive service) throws IOException {
ArrayList<File> result = new ArrayList<File>();
Files.List request = service.files().list();
request.setQ("'appdata' in parents");
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
for (File file:result){
System.out.println("##### "+file.getOriginalFilename()+ " "+file.toPrettyString());
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
InputStream in= resp.getContent();
FileOutputStream fos = openFileOutput("pinmemo",
Context.MODE_PRIVATE);
while(in.available()>0)
fos.write(in.read());
fos.close();
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
return null;
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
return result;
}
What should I do?
EDIT:
I get this error message:
04-17 11:19:30.614: W/System.err(2022): com.google.api.client.http.HttpResponseException: 401 Unauthorized
04-17 11:19:30.614: W/System.err(2022): at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1095)
EDIT: the new Google play games services basically covers my needs (the only problem is that my app isn't a game...), therefore this question is now partially obsolete. Of course, Google play games uses "Cloud save" instead of "drive", but for my needs that's sufficent. However, should I use Google play games for non-gaming app?
Make sure that your access token has permissions for the appdata scope:
https://www.googleapis.com/auth/drive.appdata