Java – How do I get Azure blobs without downloading to a local file using Java?

How do I get Azure blobs without downloading to a local file using Java?… here is a solution to the problem.

How do I get Azure blobs without downloading to a local file using Java?

(for Azure for SDK 10) I can download a file to memory, but I only want to download it to a blob or other local object.

  • There seems to be a download function for a BlockBlobURL, but this returns a Single<> object: is there a more direct way to get the blob contents?

  • This The link describes the download to a file.

  • I’m looking for The Java equivalent of this

Solution

Try it out using the sample code below to get the blob contents directly instead of the local file.

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.InputStreamReader;

public class GetBlobContent {

public static final String storageConnectionString =
            "DefaultEndpointsProtocol=http;" +
                    "AccountName=***;" +
                    "AccountKey=***";

public static void main(String[] args) {
        try {
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference("jay");
            CloudBlob blob = container.getBlockBlobReference("test.txt");
            InputStream input =  blob.openInputStream();
            InputStreamReader inr = new InputStreamReader(input, "UTF-8");
            String utf8str = IOUtils.toString(inr);
            System.out.println(utf8str);

System.out.println("download success");

} catch (Exception e) {
             Output the stack trace.
            e.printStackTrace();
        }
    }
}

Related Problems and Solutions