【Azure Developer】VS Code运行Java 版Azure Storage SDK操作Blob (新建Container, 上传Blob文件,下载及清理)

简介: 【Azure Developer】VS Code运行Java 版Azure Storage SDK操作Blob (新建Container, 上传Blob文件,下载及清理)

问题描述

是否可以用Java代码来管理Azure blob? 可以。在代码中加入azure-storage-blob依赖。即可使用以下类操作Azure Storage Blob。

  • BlobServiceClient:BlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。 存储帐户为 Blob 服务提供顶级命名空间。
  • BlobServiceClientBuilder:BlobServiceClientBuilder 类提供流畅的生成器 API,以帮助对 BlobServiceClient 对象的配置和实例化。
  • BlobContainerClient:BlobContainerClient 类可用于操纵 Azure 存储容器及其 blob。
  • BlobClient:BlobClient 类可用于操纵 Azure 存储 blob。
  • BlobItem:BlobItem 类表示从对 listBlobs 的调用返回的单个 blob。

执行步骤

首先,设置VS Code上执行Java 代码的环境,这里需要的步骤比较多。完全参考VS Code for Java文档即可:https://code.visualstudio.com/docs/java/java-tutorial.

以下是创建项目步骤:

1)创建blob-quickstart-v12项目

跳转到blob-quickstart-v12目录,并在目录中创建一个data目录,用于在接下来的代码中创建本地文件及下载bolb中的文件

cd blob-quickstart-v12
mkdir data

2)   修改pom.xml,添加对Java azure-storage-blob SDK的依赖

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-blob</artifactId>
      <version>12.6.0</version>
  </dependency>
  </dependencies>

3)在App.java代码文件中添加引用

package com.blobs.quickstart;
/**
 * Azure blob storage v12 SDK quickstart
*/
import com.azure.storage.blob.*;
import com.azure.storage.blob.models.*;
import java.io.*;
public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Blob storage v12 - Java quickstart sample\n");

 

4)添加Stroage Account的连接字符串

 

 

 

5)创建blobServiceClient对象,同时调用createBlobContainer方法创建容器

// Create a BlobServiceClient object which will be used to create a container client
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();
        //Create a unique name for the container
        String containerName = "quickstartblobs" + java.util.UUID.randomUUID();
        // Create the container and return a container client object
        BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);

6)创建BlobClient对象,同时调用uploadFromFile方法上传文件(.tx)

// Create a local file in the ./data/ directory for uploading and downloading
        String localPath = "./data/";
        String fileName = "quickstart" + java.util.UUID.randomUUID() + ".txt";
        File localFile = new File(localPath + fileName);
        // Write text to the file
        FileWriter writer = new FileWriter(localPath + fileName, true);
        writer.write("Hello, World!");
        writer.close();
        // Get a reference to a blob
        BlobClient blobClient = containerClient.getBlobClient(fileName);
        System.out.println("\nUploading to Blob storage as blob:\n\t" + blobClient.getBlobUrl());
        // Upload the blob
        blobClient.uploadFromFile(localPath + fileName);

7)使用containerClient对象的listBlobs方法列出容器中的BlobItem

System.out.println("\nListing blobs...");
        // List the blob(s) in the container.
        for (BlobItem blobItem : containerClient.listBlobs()) {
            System.out.println("\t" + blobItem.getName());
        }

 

8)使用blobClient对象的downloadToFile方法下载文件到本地

// Download the blob to a local file
        // Append the string "DOWNLOAD" before the .txt extension so that you can see both files.
        String downloadFileName = fileName.replace(".txt", "DOWNLOAD.txt");
        File downloadedFile = new File(localPath + downloadFileName);
        System.out.println("\nDownloading blob to\n\t " + localPath + downloadFileName);
        blobClient.downloadToFile(localPath + downloadFileName);

 

9)使用containerClient对象的delete方法删除容器

// Clean up
        System.out.println("\nPress the Enter key to begin clean up");
        System.console().readLine();
        System.out.println("Deleting blob container...");
        containerClient.delete();
        System.out.println("Deleting the local source and downloaded files...");
        localFile.delete();
        downloadedFile.delete();
        System.out.println("Done");

 

10) 在VS Code中调试或执行,右键选择Run/Debug

 

全部代码

App.java文件

package com.blobs.quickstart;
/**
 * Azure blob storage v12 SDK quickstart
*/
import com.azure.storage.blob.*;
import com.azure.storage.blob.models.*;
import java.io.*;
public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Blob storage v12 - Java quickstart sample\n");
        // Retrieve the connection string for use with the application. The storage
        // connection string is stored in an environment variable on the machine
        // running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable
        // is created after the application is launched in a console or with
        // Visual Studio, the shell or application needs to be closed and reloaded
        // to take the environment variable into account.
        String connectStr ="DefaultEndpointsProtocol=https;AccountName=xxxxxxxx;AccountKey=xxxxxxxxxxxxxxx;EndpointSuffix=core.chinacloudapi.cn";// System.getenv("AZURE_STORAGE_CONNECTION_STRING");
        // Create a BlobServiceClient object which will be used to create a container client
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();
        //Create a unique name for the container
        String containerName = "quickstartblobs" + java.util.UUID.randomUUID();
        // Create the container and return a container client object
        BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);
        // Create a local file in the ./data/ directory for uploading and downloading
        String localPath = "./data/";
        String fileName = "quickstart" + java.util.UUID.randomUUID() + ".txt";
        File localFile = new File(localPath + fileName);
        // Write text to the file
        FileWriter writer = new FileWriter(localPath + fileName, true);
        writer.write("Hello, World!");
        writer.close();
        // Get a reference to a blob
        BlobClient blobClient = containerClient.getBlobClient(fileName);
        System.out.println("\nUploading to Blob storage as blob:\n\t" + blobClient.getBlobUrl());
        // Upload the blob
        blobClient.uploadFromFile(localPath + fileName);
        System.out.println("\nListing blobs...");
        // List the blob(s) in the container.
        for (BlobItem blobItem : containerClient.listBlobs()) {
            System.out.println("\t" + blobItem.getName());
        }
        // Download the blob to a local file
        // Append the string "DOWNLOAD" before the .txt extension so that you can see both files.
        String downloadFileName = fileName.replace(".txt", "DOWNLOAD.txt");
        File downloadedFile = new File(localPath + downloadFileName);
        System.out.println("\nDownloading blob to\n\t " + localPath + downloadFileName);
        blobClient.downloadToFile(localPath + downloadFileName);
        // Clean up
        System.out.println("\nPress the Enter key to begin clean up");
        System.console().readLine();
        System.out.println("Deleting blob container...");
        containerClient.delete();
        System.out.println("Deleting the local source and downloaded files...");
        localFile.delete();
        downloadedFile.delete();
        System.out.println("Done");
    }
}

 

pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.blobs.quickstart</groupId>
  <artifactId>blob-quickstart-v12</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>blob-quickstart-v12</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-blob</artifactId>
      <version>12.6.0</version>
  </dependency>
  </dependencies>
  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

参考资料

Getting Started with Java in VS Code:https://code.visualstudio.com/docs/java/java-tutorial

快速入门:使用 Java v12 SDK 管理 blob: https://docs.azure.cn/zh-cn/storage/blobs/storage-quickstart-blobs-java#code-examples

相关文章
|
1月前
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
129 5
|
1月前
|
网络协议 安全 Java
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
50 0
|
4月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
4月前
|
存储 XML 开发工具
【Azure Storage Account】利用App Service作为反向代理, 并使用.NET Storage Account SDK实现上传/下载操作
本文介绍了如何在Azure上使用App Service作为反向代理,以自定义域名访问Storage Account。主要内容包括: 1. **设置反向代理**:通过配置`applicationhost.xdt`和`web.config`文件,启用IIS代理功能并设置重写规则。 2. **验证访问**:测试原生URL和自定义域名的访问效果,确保两者均可正常访问Storage Account。 3. **.NET SDK连接**:使用共享访问签名(SAS URL)初始化BlobServiceClient对象,实现通过自定义域名访问存储服务。
|
5月前
|
Java API 数据处理
深潜数据海洋:Java文件读写全面解析与实战指南
通过本文的详细解析与实战示例,您可以系统地掌握Java中各种文件读写操作,从基本的读写到高效的NIO操作,再到文件复制、移动和删除。希望这些内容能够帮助您在实际项目中处理文件数据,提高开发效率和代码质量。
119 4
|
3月前
|
JavaScript 前端开发 程序员
甚至用不了五分钟就能学会vscode插件开发
本文介绍了VSCode插件的开发流程,从创建项目到最终发布。首先通过安装`yo`和`generator-code`脚手架工具初始化项目,选择JavaScript语言配置基础信息。接着,在`extension.js`中实现业务逻辑,例如将中文“变量”替换为“var”。通过F5进入调试模式验证功能。完成后使用`vsce`工具进行打包,解决可能遇到的版本不兼容或README文档问题。最后生成`.vsix`文件,可通过VSCode的“从VSIX安装”加载插件,实现开发闭环。进一步可将插件发布至官方市场供更多开发者使用。
|
5月前
|
人工智能 自然语言处理 前端开发
通义灵码插件在VSCode中的运用
借助通义灵码插件在VSCode构建新闻网,实现效率与智能的融合。VSCode作为前端开发的“瑞士军刀”,提供实时预览、智能辅助和高效管理功能;通义灵码插件通过自然语言交互生成代码,简化复杂任务并优化代码质量。两者结合形成从设计到部署的高效闭环,大幅减少基础编码时间,降低开发门槛,助力开发者聚焦业务逻辑与创新。
|
5月前
|
人工智能 小程序 程序员
【视频测评 DEMO 参考】VSCode 神级 AI 插件通义灵码:完全免费+实战教程+微信贪吃蛇小程序
VSCode 神级 AI 插件通义灵码:完全免费+实战教程+微信贪吃蛇小程序
432 8
|
5月前
|
机器学习/深度学习 人工智能 自然语言处理
|
8月前
|
自然语言处理 API C++
阿里通义推出SmartVscode插件,自然语言控制VS Code,轻松开发应用,核心技术开源!
SmartVscode插件深度解析:自然语言控制VS Code的革命性工具及其开源框架App-Controller
1220 1
阿里通义推出SmartVscode插件,自然语言控制VS Code,轻松开发应用,核心技术开源!

热门文章

最新文章