Sakthi Ganesh
Sakthi Ganesh

Reputation: 115

How to create an empty folder in google cloud bucket using Java API

I am using the JSON API - Google API Client Library for Java to access the objects in Google Cloud Storage. I need to create (not upload) an empty folder in the bucket. Google Developer Web Console has that option to creating a directory, but neither the Java API nor the gsutil command has a create folder command. If anybody knows how to do so, please let me know. Thanks in advance...

Upvotes: 6

Views: 9672

Answers (3)

user3326197
user3326197

Reputation: 61

I think is better that you create the folder within the file name. For example if you need a folder called images and other one called docs, when you give the name of the object to upload do it in the following way images/name_of_file or docs/name_of_file.

If the name of the file is images/dogImage and you upload that file, you will find in your bucket a folder called images.

I hope to help you and others

Upvotes: 6

Daniel De León
Daniel De León

Reputation: 13639

This is my Java method to create an empty (emulated) folder:

public static void createFolder(String name) throws IOException {
    Channels.newOutputStream(
            createFile(name + "/")
    ).close();
}

public static GcsOutputChannel createFile(String name) throws IOException {
    return getService().createOrReplace(
            new GcsFilename(getName(), name),
            GcsFileOptions.getDefaultInstance()
    );
}

private static String name;

public static String getName() {
    if (name == null) {
        name = AppIdentityServiceFactory.getAppIdentityService().getDefaultGcsBucketName();
    }
    return name;
}

public static GcsService service;

public static GcsService getService() {
    if (service == null) {
        service = GcsServiceFactory.createGcsService(
                new RetryParams.Builder()
                        .initialRetryDelayMillis(10)
                        .retryMaxAttempts(10)
                        .totalRetryPeriodMillis(15000)
                        .build());
    }
    return service;
}

Upvotes: 1

Travis Hobrla
Travis Hobrla

Reputation: 5511

You can emulate a folder by uploading a zero-sized object with a trailing slash.

As noted in the question comments, Google Cloud Storage is not a filesystem and emulating folders has serious limitations.

Upvotes: 6

Related Questions