如何在Java中检查Azure Blob容器中是否存在文件

时间:2019-01-28 12:15:09

标签: java azure azure-blob-storage

我要检查文件是否在Azure Blob存储的容器中。如果文件存在,那么我将下载文件。

2 个答案:

答案 0 :(得分:1)

由于没有任何REST API或SDK API来检查blob是否存在,因此您无法直接对其进行检查。如我所知,检查blob是否存在的唯一方法是在获取blob时检查错误信息,请参阅Common REST API Error Codes,如下所示。

enter image description here

这是我使用Microsoft Azure Storage SDK v10 for Java检查斑点是否存在的步骤和示例代码。

适用于Java的Azure存储SDK v10的maven dependency如下。

<!-- https://mvnrepository.com/artifact/com.microsoft.azure/azure-storage-blob -->
<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>10.4.0</version>
</dependency>
  1. 生成具有SAS签名的Blob网址。

    String accountName = "<your storage account name>";
    String accountKey = "<your storage account key>";
    
    public String generateUrlWithSAS(String containerName, String blobName) throws InvalidKeyException {
        SharedKeyCredentials credentials = new SharedKeyCredentials(accountName, accountKey);
        ServiceSASSignatureValues values = new ServiceSASSignatureValues()
                .withProtocol(SASProtocol.HTTPS_ONLY) // Users MUST use HTTPS (not HTTP).
                .withExpiryTime(OffsetDateTime.now().plusDays(2)) // 2 days before expiration.
                .withContainerName(containerName)
                .withBlobName(blobName);
        BlobSASPermission permission = new BlobSASPermission()
                .withRead(true)
                .withAdd(true)
                .withWrite(true);
        values.withPermissions(permission.toString());
        SASQueryParameters serviceParams = values.generateSASQueryParameters(credentials);
        String sasSign = serviceParams.encode();
        return String.format(Locale.ROOT, "https://%s.blob.core.windows.net/%s/%s%s", accountName, containerName, blobName, sasSign);
    }
    
  2. 对具有SAS签名的URL发出Http Head请求,以检查响应状态代码

    public static boolean exists(String urlWithSAS) throws MalformedURLException, IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlWithSAS).openConnection();
        conn.setRequestMethod("HEAD");
        return conn.getResponseCode() == 200;
    }
    

另外,您可以在下载blob时通过捕获相关异常直接检查是否存在。

答案 1 :(得分:0)

在@Peter Pan的答案的启发下,如果您是Blob所有者,那么更简单(对我来说也不太混乱)。

boolean blobExists(String containerName, String blobName) {
    ServiceURL serviceUrl = getServiceUrl();
    HttpURLConnection httpUrlConnection = (HttpURLConnection)
        serviceUrl.createContainerURL(containerName)
            .createBlockBlobURL(blobName)
            .toURL().openConnection();
    httpUrlConnection.setRequestMethod("HEAD");
    return httpUrlConnection.getResponseCode() / 100 == 2;
}

ServiceURL getServiceUrl() {
    SharedKeyCredentials credentials = new SharedKeyCredentials(accountName, accountKey);
    return new ServiceURL(new URL(azureUrl), StorageURL.createPipeline(credentials, new PipelineOptions()));
}

经过库com.microsoft.azure:azure-storage-blob:10.5.0的测试。