I want to get all file name from google drive using java. I get file which is uploaded from my java application but i want to get all file which is uploaded from other resources.
Drive driveService = new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
.setApplicationName(APPLICATION_NAME)
.build();
String pageToken = null;
do {
FileList files = driveService.files().list()
.setFields("nextPageToken, files(id, name, parents)")
.setSpaces("drive")
.setPageToken(pageToken)
.execute();
String drivefile = "";
System.out.println("file ::: " + driveService.files().list().execute());
for (File file : files.getFiles()) {
drivefile = file.getName() + "," + drivefile;
}
Please tell me how can i get all file name..
Related
I'm able to upload files on Google Cloud Storage using Firebase Admin SDK. However, I'm unable to set the correct contentType for the file and the uploaded file defaults to application/octet-stream. I'm unable to any documentations for setting the correct contentType/metadata using Java Admin SDK. How I can change the default contentType?
Here's the code snippet on how I upload the file.
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timestamp = dateFormat.format(date);
StorageClient storageClient = StorageClient.getInstance();
Bucket storageBucket = storageClient.bucket();
// Not sure if I'm doing this correctly
BlobInfo blobInfo = BlobInfo.newBuilder(storageBucket.getName(), "filename")
.setContentType("vnd.ms-excel").build();
// File upload task
storageClient.bucket().create(backupFolderPath + fileNamePrefix + "_" + timestamp + ".csv", file);
Turns out that I need to use Google Cloud Storage API. The docs for Firebase Cloud Storage for Admin SDK is barren. I hope that the docs were clearer.
Here's the snippet on how I modified the contentType for my file upload. This changed the contentType from application/octet-stream to text/csv
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timestamp = dateFormat.format(date);
StorageClient storageClient = StorageClient.getInstance();
try {
String bucketName = "<YOUR_BUCKET_NAME>";
String objectName = backupFolderPath + fileNamePrefix + "_" + timestamp + ".csv";
BlobId blobId = BlobId.of(bucketName, objectName);
// Configure BlobInfo
BlobInfo blob = BlobInfo.newBuilder(blobId)
.setContentType("text/csv")
.setContentEncoding("utf-8").build();
// Use fetch `storage` from the bucket
// https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-code-sample
storageClient.bucket().getStorage().create(blob,
Files.readAllBytes(Paths.get("backup/accounts.csv")));
} catch (IOException e) {
logger.error(">>>>> Message from Scheduled Job " + e);
}
I'm still unable to download the uploaded file on Firebase Storage dashboard, but the uploaded file can be downloaded through Google Cloud Storage dashboard.
I'm able to download excel file by clicking Download button which comes under DOM ,
after that i want verify downloaded file is same one.
AUTO IT is not allowed in project.
I have tried below code for verification on local but if i will push this code to repo.
then user path will get change and code will fail.
`String filepath = "C:User\\Dhananjay\\Downloads";
String fileName = "report.xlsx"
File targetFile = new File(fileName,filePath);
if(! targetFile.exists())'
{
system.out.println("File is verified")`
}else{
system.out.println("file not downloaded")
}'
String userProfile = System.getProperty("user.home"); returns %USERPROFILE% variable.
So you can use String filepath = System.getProperty("user.home") + "\\Downloads";
Works even on Linux.
I have found way to validate on local path and it's generic one
File folder = new File(System.getProperty("user.home") +\\Downloads);
File[] listOfFiles = folder.listFiles();
boolean found = false;
File f = null;
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
String fileName = listOfFile.getName();
System.out.println("File " + listOfFile.getName());
if (fileName.matches("5MB.zip")) {
f = new File(fileName);
found = true;
}
}
}
Assert.assertTrue("Downloaded document is not found",found );
f.deleteOnExit();
I'm learning about Google Api for uploading file on Android and did find the good sample about it.(you can take a look on that sample here:
https://github.com/sdivakarrajesh/Uploading-Files-to-Google-drive-using-java-client-api-in-Android/blob/master/app/src/main/java/com/dev/theblueorb/usingdrivejavaapi/DriveActivity.java)
However, it's only show how to upload files, not how to select the file and upload it to GG drive. Here are the code for uploading and creating folder on GG drive:
private void uploadFile() throws IOException {
File fileMetadata = new File();;
fileMetadata.setName("Sample File");
fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
// For mime type of specific file visit Drive Doucumentation
file2 = new java.io.File(path);
InputStream inputStream = getResources().openRawResource(R.raw.template);
try {
FileUtils.copyInputStreamToFile(inputStream,file2);
} catch (IOException e) {
e.printStackTrace();
}
FileContent mediaContent = new FileContent("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",file2);
File file = mService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
Log.e(this.toString(),"File Created with ID:"+ file.getId());
Toast.makeText(getApplicationContext(),
"File created:"+file.getId() , Toast.LENGTH_SHORT).show();
}
}
private void createFolderInDrive() throws IOException {
File fileMetadata = new File();
fileMetadata.setName("Sample Folder");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Log.e(this.toString(),"Folder Created with ID:"+ file.getId());
Toast.makeText(getApplicationContext(),
"Folder created:"+file.getId() , Toast.LENGTH_SHORT).show();
}
Any body knows how to select the file on device, then upload it to selected folder on GG drive or the sample for that?
Referencing these docs for basic file upload, you should be able to "select the file on device" by specifying the complete file path as fileName in this line below:
java.io.File fileContent = new java.io.File(filename);.
For example, if you had a file called coolpic inside the directory media, you could use media/coolpic for the filename. The next doc I reference reinforces this strategy. The path will depend on the root location which, is something you can easily investigate.
Then, check out this doc for working with folders in Google Drive. You'll want to find the folder id and set this on upload using
fileMetadata.setParents(Collections.singletonList(folderId));
Note you can upload and then move in two steps, or use my method above and set the folder on upload.
I'm trying to save a file to external storage, however it's giving the FileNotFoundException error.
Note: I've already made the changes to Android Manifest.
File file = null;
if (isExternalStorageWritable()) {
Log.d("SEND", "Entrou no IF do ExernalStorage");
//File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File path = ContaListFragment.this.getActivity()
.getApplicationContext()
.getExternalFilesDir(
Environment.DIRECTORY_PICTURES);//getExternalFilesDir
file = new File(path, "file.json");
//Make sure the Pictures directory exists.
Log.d("SEND", "" + path.mkdir() + " PATH=" + file.getAbsolutePath());
//file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "file.json");
}
if (!file.mkdirs()) {
Log.d("SEND", "Directory not created");
}
if (!isExternalStorageWritable()) {
file = new File(ContaListFragment.this.getActivity()
.getApplicationContext().getFilesDir(), "file.json");
Log.d("SEND", "Passei do File");
output = new BufferedWriter(new FileWriter(file));
Log.d("SEND", "Passou do Buffered");
output.write(jsonObject.toString());
uri = Uri.fromFile(file);
}
The issue was resolved with the help of:
See the answers to this question
The problem was that I was creating a directory instead of a file. Just replace: file.mkdirs(); with file.createNewFile();
there is folder temp to which the files uploaded by users are stored. the file name is same for each user but the content is different. Each user uploads a file called abc.xlsx. now when "A" user uploads abc.xlsx file after processing that file should be deleted. But currently i am deleting all the files in the folder. which is a problem since one more user might be uploading the file ehich will be cleared too. So i was thinking of renaming the file by appending the username to the file and then delete that particular file.
This is the file upload:
ProcessForm uploadForm = (ProcessForm)form;
String folderpath = "servers/temp";
String filePath = folderpath + "/" + uploadForm.getUploadedFile().getFileName();
This will delete all the files in the folder:
String tempPath = folderpath;
File file = new File(tempPath);
File[] files = file.listFiles();
for (File f:files)
{
if (f.isFile() && f.exists())
{
f.delete();
}
}
I think i got it. This is working as expected:
String folderpath = "servers/temp";
String filePath = folderpath + "/" + "abc_"+user.getUsername()+".xlsx";
outputStream = new FileOutputStream(new File(filePath));
outputStream.write(uploadForm.getUploadedFile().getFileData());
Code to delete file:
File file = new File(filePath);
boolean fileDelete = file.delete();
if (fileDelete)
{
mLogger.debug("successfully deleted");
} else {
mLogger.error("cant delete a file");
}