Mohit Singh
Mohit Singh

Reputation: 477

How to move file between azure blob containers using java?

How i can move file from one blob container to another using java api.

i am using below SKD from microsoft.

Gradle dependency: compile group: 'com.azure', name: 'azure-storage-blob', version: '12.8.0'
 

how i can move a file between blob storage using java api.

Upvotes: 0

Views: 2379

Answers (1)

unknown
unknown

Reputation: 7473

BlobClientBase.beginCopy Method is used to copy the data at the source URL to a blob.

Code sample:

If the containers are in the different storage accounts:

String connectStr = "source storage account connection string";
String destconnectStr="destination storage account connection string";

// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();

BlobServiceClient destblobServiceClient = new BlobServiceClientBuilder().connectionString(destconnectStr).buildClient();

BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("test");

BlobContainerClient destcontainer=destblobServiceClient.getBlobContainerClient("destcontainer");

PagedIterable<BlobItem> blobs= containerClient.listBlobs();
for (BlobItem blobItem : blobs) {

    System.out.println("This is the blob name: " + blobItem.getName());
    BlobClient blobClient=containerClient.getBlobClient(blobItem.getName());
    BlobClient destblobclient=destcontainer.getBlobClient(blobItem.getName());
    destblobclient.beginCopy(blobClient.getBlobUrl(),null);

}

If the containers are in the same storage account:

String connectStr = "storage account connection string";

// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();

BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("test");

BlobContainerClient destcontainer=blobServiceClient.getBlobContainerClient("testcontainer");

PagedIterable<BlobItem> blobs= containerClient.listBlobs();
for (BlobItem blobItem : blobs) {

    System.out.println("This is the blob name: " + blobItem.getName());
    BlobClient blobClient=containerClient.getBlobClient(blobItem.getName());
    BlobServiceSasSignatureValues sas = new BlobServiceSasSignatureValues(OffsetDateTime.now().plusHours(1),
    BlobContainerSasPermission.parse("r"));
    String sasToken = blobClient.generateSas(sas);

    BlobClient destblobclient=destcontainer.getBlobClient(blobItem.getName());
    destblobclient.beginCopy(blobClient.getBlobUrl()+ "?" + sasToken,null);

}

BlobClientBase.copyFromUrl Method can also be used for this, but it will wait for the copy to complete before returning a response. You could choose what you need.

Upvotes: 2

Related Questions