从blob存储下载虚拟目录

时间:2018-01-16 05:38:53

标签: java azure azure-storage-blobs

我想从Azure blob存储下载虚拟目录。目录存在于容器中。我尝试使用ColudBlobDirectory API。但它没有任何下载虚拟目录的方法。

for (ListBlobItem blobItem : container.listBlobs()) { 
    // If the item is a blob, a virtual directory. 
    if (blobItem instanceof CloudBlobDirectory) { 
        CloudBlobDirectory blob1 = (CloudBlobDirectory) blobItem; 
        System.out.println("\n Blob prefix:" + blob1.getPrefix()); 
    }
}

1 个答案:

答案 0 :(得分:0)

正如@talex所说,你可以从目录中逐个下载blob文件,如下所示:

public static String destFilePath = "/path/to/directory/";

public static void main(String[] args)
        throws InvalidKeyException, URISyntaxException, StorageException, IOException {

    CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
    CloudBlobClient serviceClient = account.createCloudBlobClient();
    CloudBlobContainer container = serviceClient.getContainerReference("mycontainer");

    for (ListBlobItem blobItem : container.listBlobs()) {

        // If the item is a blob, a virtual directory.
        if (blobItem instanceof CloudBlobDirectory) {

            CloudBlobDirectory blobDir = (CloudBlobDirectory) blobItem;
            downloadDirectory(blobDir);
        }
    }
}

public static void downloadDirectory(CloudBlobDirectory blobDir)
        throws IOException, StorageException, URISyntaxException {

    Files.createDirectories(Paths.get(destFilePath + blobDir.getPrefix()));

    for (ListBlobItem blobInDir : blobDir.listBlobs()) {

        if (blobInDir instanceof CloudBlockBlob) {
            CloudBlockBlob blob = (CloudBlockBlob) blobInDir;
            blob.downloadToFile(destFilePath + blob.getName());
        } else {
            downloadDirectory((CloudBlobDirectory) blobInDir);
        }
    }

}