gpt4 book ai didi

java - 如何用java检查文件是否存在于Azure Blob容器中

转载 作者:行者123 更新时间:2023-12-02 10:20:08 25 4
gpt4 key购买 nike

我想检查Azure Blob存储的容器中是否存在该文件。如果该文件存在,则我下载该文件。

最佳答案

由于没有任何 REST API 或 SDK API 来检查 Blob 是否存在,因此您无法直接检查它。据我所知,检查 blob 是否存在的唯一方法是检查获取 blob 时的错误信息。请引用Common REST API Error Codes ,如下。

enter image description here

以下是我使用 Microsoft Azure Storage SDK v10 for Java 检查 blob 是否存在的步骤和示例代码.

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

<!-- 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 URL。

     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 时通过捕获相关异常来直接检查是否存在。

关于java - 如何用java检查文件是否存在于Azure Blob容器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54401827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com