问题描述

是否可以用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

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

  1. Java版 人脸识别SDK demo

    虹软人脸识别SDK之Java版,支持SDK 1.1+,以及当前最新版本2.0,滴滴,抓紧上车! 前言 由于业务需求,最近跟人脸识别杠上了,本以为虹软提供的SDK是那种面向开发语言的,结果是一堆dll· ...

  2. Java版 人脸识别SDK dem

    虹软人脸识别SDK之Java版,支持SDK 1.1+,以及2.0版本,滴滴,抓紧上车! 前言由于业务需求,最近跟人脸识别杠上了,本以为虹软提供的SDK是那种面向开发语言的,结果是一堆dll······ ...

  3. azure 上传blob到ams(CreateFromBlob)

    遇到的错误:The destination storage credentials must contain the account key credentials,参数名: destinationS ...

  4. Azure IoT Hub 十分钟入门系列 (4)- 实现从设备上传日志文件/图片到 Azure Storage

    本文主要分享一个案例: 10分钟内通过Device SDK上传文件到IoTHub B站视频:https://www.bilibili.com/video/av90224073/ 本文主要有如下内容: ...

  5. 【Web应用】JAVA网络上传大文件报500错误

    问题描述 当通过 JAVA 网站上传大文件,会报 500 错误. 问题分析 因为 Azure 的 Java 网站都是基于 IIS 转发的,所以我们需要关注 IIS 的文件上传限制以及 requestT ...

  6. 用java 代码下载Samba服务器上的文件到本地目录以及上传本地文件到Samba服务器

    引入: 在我们昨天架设好了Samba服务器上并且创建了一个 Samba 账户后,我们就迫不及待的想用JAVA去操作Samba服务器了,我们找到了一个框架叫 jcifs,可以高效的完成我们工作. 实践: ...

  7. java+上传大文件

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 先说下要求: PC端全平台支持,要求支持Windows,Mac,Linux 支持所 ...

  8. java上传超大文件解决方案

    用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/1269085759/up6-jsp-mysq ...

  9. java 上传大文件以及文件夹

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...

随机推荐

  1. 理解 Linux 的硬链接与软链接(转)

    Linux 的文件与目录 现代操作系统为解决信息能独立于进程之外被长期存储引入了文件,文件作为进程创建信息的逻辑单元可被多个进程并发使用.在 UNIX 系统中,操作系统为磁盘上的文本与图像.鼠标与键盘 ...

  2. Mysql事物与二阶段提交

     1.事务的四种特性(ACID) 事务可以是一个非常简单的SQL构成,也可以是一组复杂的SQL语句构成.事务是访问并且更新数据库中数据的一个单元,在事务中的操作,要么都修改,要么都不做修改,这就是事务 ...

  3. yum安装Ceph指定Jewel版本

    前言 通过yum安装指定的rpm包,这个一般是 yum --showduplicates list ceph | expand ,然后去通过yum安装指定的版本即可,这个在hammer下是没有问题的, ...

  4. DevOps,你真的了解吗?

    与大数据和PRISM(NSA的监控项目之一),DevOps(开发运维)如今是科技人士挂在嘴边的热词,但遗憾的是,类似圣经,每个人都引用DevOps的只言片语,但真正理解并能执行的人极少.根据CA的一项 ...

  5. mysql之多表查询的其他查询

    1,临时表查询 (1)需求:查询高于本部门平均工资的人员 select * from person as p, (select dept_id, avg(salary) as '平均工资' from ...

  6. 面试半年!三面阿里,四面蚂蚁金服,居然倒在了一个Java集合之Map上?

    Map接口 Map与Collection并列存在.用于保存具有映射关系的数据:key-valueMap中的key和value都可以是任何引用类型的数据Map中的key用set来存放,不允许重复,即同一 ...

  7. Guitar Pro怎么导出乐谱

    使用Guitar Pro可以自由创作乐谱,也能根据演示效果来作出相应调整,算得上是公认的良心吉他谱制作软件.除了系统演示功能外,Guitar Pro还能给用户的实际练习提供便利.必要时,用户能将软件内 ...

  8. 如何使用ABBYY FineReader 处理无法识别的字符?

    在识别PDF文档时,我们可能会遇到文档中存在多种语言.多种不同类型文字字符的情况.在ABBYY FineReader 15(Windows系统)OCR文字识别软件的默认语言数据下,可能无法识别PDF文 ...

  9. web自动化 下拉框、切换到新窗口

    一.下拉框 相信大家在手动测试web页面时,遇到过下拉框吧,那进行web自动化测试时,如何操作下拉框,且看下文 1.selenium中提供了方法,先导入Select方法 from selenium.w ...

  10. 对于this和当前线程的一些理解

    在学习这个InheritableThreadLocal类的时候,我对于有个地方一直没有理解,我发现了盲点. 1 private void init(ThreadGroup g, Runnable ta ...