Search This Blog

Breaking

Saturday, 26 March 2022

Azure -> Java -> How to download a file present inside a azure container folder ?

If you want to download a file from a Azure container folder, you can easily do it by using azure API's. The correct way to download a file from azure container folder is to first ensure that the container is present or not.

So if you want to check that the container is available or not, please check this post










Once you have ensured that the container is present, you can use method:

 public static void downloadFile(String containerName, String fileName) {
        String fileFromContainer = "";
        BlobServiceClient blobServiceClient = createBlobServiceClient();
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
        for (BlobItem blobItem : containerClient.listBlobs()) {
            if(blobItem.getName().contains("/")) {
                fileFromContainer = StringUtils.substringAfterLast(blobItem.getName(), "/");
            } else {
                fileFromContainer = blobItem.getName();
            }

            try {
                if (fileFromContainer.contains(fileName)) {
                    BlobClient blobClient = containerClient.getBlobClient(blobItem.getName());
                    File downloadedFile = new File(downloadedPath + fileFromContainer);
                    System.out.println("\nDownloading blob to\n\t " + downloadedFile);
                    blobClient.downloadToFile(downloadedFile.toString());
                }
            } catch (Exception e) {
            }
        }
    }

downloaded file path will be your local folder path.

static String downloadedPath = "data\\downloaded\\";


No comments:

Post a Comment