Skip to content

Instantly share code, notes, and snippets.

@hkarakose
Last active June 22, 2018 20:31
Show Gist options
  • Save hkarakose/d8f9ff78f7deb692e5302e06e8612ca6 to your computer and use it in GitHub Desktop.
Save hkarakose/d8f9ff78f7deb692e5302e06e8612ca6 to your computer and use it in GitHub Desktop.
Display list of files/folders in a Google Cloud Storage(GSC) bucket
import com.google.cloud.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.labsite.repository.StorageFactory;
import java.util.Iterator;
/**
* User: Halil Karakose
* Date: 31/01/17
* Time: 21:31
*/
public class ListFilesAndFoldersInBucket {
private static final String BUCKET_NAME = "ENTER_YOUR_BUCKET_NAME_HERE";
private static final String SERVICE_ACCOUNT_KEY = "ENTER_YOUR_SERVICE_ACCOUNT_KEY";
private static final String project_id = "ENTER_YOUR_PROJECT_ID";
public static void main(String[] args) {
list("");
}
public static void list(String directory){
Storage storage = storageService();
Page<Blob> blobs = storage.list(BUCKET_NAME, Storage.BlobListOption.currentDirectory(), Storage.BlobListOption.prefix(directory));
Iterable<Blob> blobIterator = blobs.iterateAll();
blobIterator.forEach(blob -> {
if (blob.isDirectory()) {
list(blob.getName());
} else {
System.out.println(blob.getName());
}
});
}
public static Storage storageService() {
ServiceAccountCredentials oauth2 = null;
try {
oauth2 = ServiceAccountCredentials.fromStream(new StringBufferInputStream(SERVICE_ACCOUNT_KEY));
} catch (IOException e) {
throw new RuntimeException(e);
}
return StorageOptions.newBuilder()
.setCredentials(oauth2)
.setProjectId(project_id)
.build()
.getService();
}
}
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud</artifactId>
<version>0.18.0-alpha</version>
</dependency>
@balajeeven
Copy link

@sateesh6151 - Did you get the libraries used in the above example. I'm unable to resolve the dependencies for 'StorageFactory' and 'Page' classes in my Eclipse project. please help me getting this code functional.

@hkarakose
Copy link
Author

hkarakose commented Jul 24, 2017

I updated gist.
You may acquire required dependencies if you use com.google.cloud:google-cloud:0.18.0-alpha

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment