您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Java v8 SDK 管理 blobQuickstart: Manage blobs with Java v8 SDK

01/19/2021

本文内容

本快速入门介绍如何使用 Java 管理 blob。In this quickstart, you learn to manage blobs by using Java. Blob 是可以保存大量文本或二进制数据(包括图像、文档、流媒体和存档数据)的对象。Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. 你将上传、下载并列出 blob。You'll upload, download, and list blobs. 你还将创建容器、设置容器权限并删除容器。You'll also create, set permissions on, and delete containers.

备注

此快速启动使用 Azure Blob 存储客户端库的旧版本。This quickstart uses a legacy version of the Azure Blob storage client library. To get started with the latest version, see Quickstart: Manage blobs with Java v12 SDK.

先决条件Prerequisites

具有活动订阅的 Azure 帐户。An Azure account with an active subscription.

一个 Azure 存储帐户。An Azure Storage account.

包含 Maven 集成的 IDE。An IDE that has Maven integration. 本指南使用具有“适用于 Java 开发者的 Eclipse IDE”配置的 Eclipse。This guide uses Eclipse with the "Eclipse IDE for Java Developers" configuration.

下载示例应用程序Download the sample application

示例应用程序是基本的控制台应用程序。The sample application is a basic console application.

使用 git 可将应用程序的副本下载到开发环境。Use git to download a copy of the application to your development environment.

git clone https://github.com/Azure-Samples/storage-blobs-java-quickstart.git

此命令会将存储库克隆到本地 git 文件夹。This command clones the repository to your local git folder. 若要打开项目,请启动 Eclipse 并关闭欢迎屏幕。To open the project, launch Eclipse and close the Welcome screen. 选择“文件”,然后选择“从文件系统打开项目”。Select File then Open Projects from File System. 请确保已选中“检测并配置项目性质”。Make sure Detect and configure project natures is checked. 选择“目录”,然后导航到存储克隆存储库的位置。Select Directory then navigate to where you stored the cloned repository. 在克隆的存储库中,选择 blobAzureApp 文件夹。Inside the cloned repository, select the blobAzureApp folder. 请确保 blobAzureApp 项目显示为 Eclipse 项目,然后选择“完成”。Make sure the blobAzureApp project appears as an Eclipse project, then select Finish.

完成项目导入后,打开 AzureApp.java(位于 src/main/java 内的 blobQuickstart.blobAzureApp 中),并替换 storageConnectionString 字符串中的 accountname 和 accountkey 。Once the project completes importing, open AzureApp.java (located in blobQuickstart.blobAzureApp inside of src/main/java), and replace the accountname and accountkey inside of the storageConnectionString string. 然后运行应用程序。Then run the application. 以下部分是有关如何完成这些任务的具体说明。Specific instructions for completing these tasks are described in the following sections.

从 Azure 门户复制凭据Copy your credentials from the Azure portal

此示例应用程序需对存储帐户访问进行身份验证。The sample application needs to authenticate access to your storage account. 若要进行身份验证,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authenticate, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

找到自己的存储帐户。Locate your storage account.

在存储帐户概述的“设置”部分,选择“访问密钥”。In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

配置存储连接字符串Configure your storage connection string

在应用程序中,必须为存储帐户提供连接字符串。In the application, you must provide the connection string for your storage account. 打开 AzureApp.Java 文件。Open the AzureApp.Java file. 找到 storageConnectionString 变量,然后粘贴在上一部分复制的连接字符串值。Find the storageConnectionString variable and paste the connection string value that you copied in the previous section. storageConnectionString 变量看起来应该类似于以下代码示例:Your storageConnectionString variable should look similar to the following code example:

public static final String storageConnectionString =

"DefaultEndpointsProtocol=https;" +

"AccountName=;" +

"AccountKey=";

运行示例Run the sample

此示例应用程序在默认目录(对于 Windows 用户,为 C:\Users\AppData\Local\Temp)中创建一个测试文件,将其上传到 Blob 存储,列出容器中的 Blob,然后下载具有新名称的文件,以便比较旧文件和新文件。This sample application creates a test file in your default directory (C:\Users\AppData\Local\Temp, for Windows users), uploads it to Blob storage, lists the blobs in the container, then downloads the file with a new name so you can compare the old and new files.

使用 Maven 在命令行运行示例。Run the sample using Maven at the command line. 打开 shell 并导航到已克隆目录中的 blobAzureApp。Open a shell and navigate to blobAzureApp inside of your cloned directory. 然后输入 mvn compile exec:java。Then enter mvn compile exec:java.

如果打算在 Windows 上运行应用程序,请参阅以下示例显示的输出。The following example shows the output if you were to run the application on Windows.

Azure Blob storage quick start sample

Creating container: quickstartcontainer

Creating a sample file at: C:\Users\\AppData\Local\Temp\sampleFile514658495642546986.txt

Uploading the sample file

URI of blob is: https://myexamplesacct.blob.core.windows.net/quickstartcontainer/sampleFile514658495642546986.txt

The program has completed successfully.

Press the 'Enter' key while in the console to delete the sample files, example container, and exit the application.

Deleting the container

Deleting the source, and downloaded files

检查示例文件的默认目录(对于 Windows 用户,为 C:\Users\AppData\Local\Temp),再继续操作。Before you continue, check your default directory (C:\Users\AppData\Local\Temp, for Windows users) for the sample file. 从控制台窗口复制 blob 的 URL,将其粘贴到浏览器,查看 Blob 存储中的文件的内容。Copy the URL for the blob out of the console window and paste it into a browser to view the contents of the file in Blob storage. 如果将目录中的示例文件与 Blob 存储中的内容进行比较,则会发现它们是相同的。If you compare the sample file in your directory with the contents stored in Blob storage, you will see that they are the same.

备注

还可以使用工具(如 Azure 存储资源管理器)查看 Blob 存储中的文件。You can also use a tool such as the Azure Storage Explorer to view the files in Blob storage. Azure 存储资源管理器是免费的跨平台工具,可用于访问存储帐户信息。Azure Storage Explorer is a free cross-platform tool that allows you to access your storage account information.

验证文件后,按 Enter 键可完成演示并删除测试文件。After you've verified the files, press the Enter key to complete the demo and delete the test files. 现在已了解此示例的用途,打开 AzureApp.java 文件可查看代码。Now that you know what the sample does, open the AzureApp.java file to look at the code.

了解示例代码Understand the sample code

接下来逐步介绍示例代码,以便展示其工作方式。Next, we walk through the sample code so that you can understand how it works.

获取对存储对象的引用Get references to the storage objects

首先创建对用于访问和管理 Blob 存储的对象的引用。The first thing to do is create the references to the objects used to access and manage Blob storage. 这些对象相互关联 - 每个对象被列表中的下一个对象使用。These objects build on each other -- each is used by the next one in the list.

Create an instance of the CloudStorageAccount object pointing to the storage account.

“CloudStorageAccount”对象是存储帐户的表示形式,允许用户以编程方式设置和访问存储帐户属性。The CloudStorageAccount object is a representation of your storage account and it allows you to set and access storage account properties programmatically. 使用“CloudStorageAccount”对象,可创建访问 blob 服务所需的“CloudBlobClient”实例 。Using the CloudStorageAccount object you can create an instance of the CloudBlobClient, which is necessary to access the blob service.

创建 CloudBlobClient 对象的实例,该对象指向存储帐户中的 Blob 服务。Create an instance of the CloudBlobClient object, which points to the Blob service in your storage account.

“CloudBlobClient”提供对 Blob 服务的访问点,允许用户以编程方式设置和访问 Blob 存储属性。The CloudBlobClient provides you a point of access to the blob service, allowing you to set and access Blob storage properties programmatically. 使用“CloudBlobClient”,可创建“CloudBlobContainer”对象的实例,创建容器需要该实例 。Using the CloudBlobClient you can create an instance of the CloudBlobContainer object, which is necessary to create containers.

创建 CloudBlobContainer 对象的实例,该对象代表所访问的容器。Create an instance of the CloudBlobContainer object, which represents the container you are accessing. 使用容器来组织 Blob,就像使用计算机上的文件夹组织文件一样。Use containers to organize your blobs like you use folders on your computer to organize your files.

有了 CloudBlobContainer 后,就可以创建 CloudBlockBlob 对象(该对象指向你感兴趣的特定 Blob)的实例,然后执行上传、下载、复制等操作。Once you have the CloudBlobContainer, you can create an instance of the CloudBlockBlob object that points to the specific blob you're interested in, and perform an upload, download, copy, or other operation.

重要

容器名称必须为小写。Container names must be lowercase.

创建容器Create a container

在本部分中,将创建对象的实例、创建新容器,并对容器设置权限,使 blob 公开,只需 URL 即可对其进行访问。In this section, you create an instance of the objects, create a new container, and then set permissions on the container so the blobs are public and can be accessed with just a URL. 容器名为 quickstartcontainer。The container is called quickstartcontainer.

此示例使用 CreateIfNotExists,因为我们想要每次运行示例时都创建新容器。This example uses CreateIfNotExists because we want to create a new container each time the sample is run. 在生产环境中,应用程序从头至尾都使用相同的容器,因此建议仅调用一次 CreateIfNotExists。In a production environment, where you use the same container throughout an application, it's better practice to only call CreateIfNotExists once. 或者可以提前创建容器,这样就无需在代码中创建它。Alternatively, you can create the container ahead of time so you don't need to create it in the code.

// Parse the connection string and create a blob client to interact with Blob storage

storageAccount = CloudStorageAccount.parse(storageConnectionString);

blobClient = storageAccount.createCloudBlobClient();

container = blobClient.getContainerReference("quickstartcontainer");

// Create the container if it does not exist with public access.

System.out.println("Creating container: " + container.getName());

container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());

将 blob 上传到容器Upload blobs to the container

若要将文件上传到块 Blob,请获取对目标容器中的 Blob 的引用。To upload a file to a block blob, get a reference to the blob in the target container. 有了 blob 引用后,可以通过使用 CloudBlockBlob.Upload 将数据上传到其中。Once you have the blob reference, you can upload data to it by using CloudBlockBlob.Upload. 此操作会创建 Blob(如果尚未存在),或者覆盖 Blob(若已存在)。This operation creates the blob if it doesn't already exist, or overwrites the blob if it already exists.

示例代码创建一个用于上传和下载的本地文件,存储作为“源”上传的文件和 blob 中的 blob 名称。The sample code creates a local file to be used for the upload and download, storing the file to be uploaded as source and the name of the blob in blob. 以下示例将文件上传到名为“quickstartcontainer”的容器。The following example uploads the file to your container called quickstartcontainer.

//Creating a sample file

sourceFile = File.createTempFile("sampleFile", ".txt");

System.out.println("Creating a sample file at: " + sourceFile.toString());

Writer output = new BufferedWriter(new FileWriter(sourceFile));

output.write("Hello Azure!");

output.close();

//Getting a blob reference

CloudBlockBlob blob = container.getBlockBlobReference(sourceFile.getName());

//Creating blob and uploading file to it

System.out.println("Uploading the sample file ");

blob.uploadFromFile(sourceFile.getAbsolutePath());

There are several upload methods including upload, uploadBlock, uploadFullBlob, uploadStandardBlobTier, and uploadText which you can use with Blob storage. 例如,如果有字符串,可以使用 UploadText 方法,而不是 Upload 方法。For example, if you have a string, you can use the UploadText method rather than the Upload method.

块 blob 可以是任何类型的文本或二进制文件。Block blobs can be any type of text or binary file. 页 Blob 主要用于支持 IaaS VM 的 VHD 文件。Page blobs are primarily used for the VHD files that back IaaS VMs. 将追加 Blob 用于日志记录,例如有时需要写入到文件,再继续添加更多信息。Use append blobs for logging, such as when you want to write to a file and then keep adding more information. 存储在 Blob 存储中的大多数对象都是块 blob。Most objects stored in Blob storage are block blobs.

列出容器中的 BlobList the blobs in a container

You can get a list of files in the container using CloudBlobContainer.ListBlobs. 下面的代码检索 blob 列表,然后循环访问它们,显示找到的 blob 的 URI。The following code retrieves the list of blobs, then loops through them, showing the URIs of the blobs found. 可以从命令窗口中复制 URI,然后将其粘贴到浏览器以查看文件。You can copy the URI from the command window and paste it into a browser to view the file.

//Listing contents of container

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

System.out.println("URI of blob is: " + blobItem.getUri());

}

下载 BlobDownload blobs

Download blobs to your local disk using CloudBlob.DownloadToFile.

以下代码下载上一部分上传的 blob,对 blob 名称添加“_DOWNLOADED”后缀,以便可以在本地磁盘上看到两个文件。The following code downloads the blob uploaded in a previous section, adding a suffix of "_DOWNLOADED" to the blob name so you can see both files on local disk.

// Download blob. In most cases, you would have to retrieve the reference

// to cloudBlockBlob here. However, we created that reference earlier, and

// haven't changed the blob we're interested in, so we can reuse it.

// Here we are creating a new file to download to. Alternatively you can also pass in the path as a string into downloadToFile method: blob.downloadToFile("/path/to/new/file").

downloadedFile = new File(sourceFile.getParentFile(), "downloadedFile.txt");

blob.downloadToFile(downloadedFile.getAbsolutePath());

清理资源Clean up resources

If you no longer need the blobs that you have uploaded, you can delete the entire container using CloudBlobContainer.DeleteIfExists. 此方法也会删除容器中的文件。This method also deletes the files in the container.

try {

if(container != null)

container.deleteIfExists();

} catch (StorageException ex) {

System.out.println(String.format("Service error. Http code: %d and error code: %s", ex.getHttpStatusCode(), ex.getErrorCode()));

}

System.out.println("Deleting the source, and downloaded files");

if(downloadedFile != null)

downloadedFile.deleteOnExit();

if(sourceFile != null)

sourceFile.deleteOnExit();

后续步骤Next steps

本文介绍如何使用 Java 在本地磁盘和 Azure Blob 存储之间传输文件。In this article, you learned how to transfer files between a local disk and Azure Blob storage using Java. 若要详细了解 Java 的用法,请转到 GitHub 源代码存储库。To learn more about working with Java, continue to our GitHub source code repository.

java azure blob 查询_快速入门:适用于 Java 的 Azure Blob 存储客户端库 v8 | Microsoft Docs...相关推荐

  1. java akka 教程_快速入门 Akka Java 指南

    快速入门 Akka Java 指南 Akka 是一个用于在 JVM 上构建高并发.分布式和容错的事件驱动应用程序的运行时工具包.Akka 既可以用于 Java,也可以用于 Scala.本指南通过描述 ...

  2. java mongodb 时间查询_Spring-Data-MongoDB快速入门

    随着MongoDB不断更新完善,尤其增加ACID的支持,越来越多的应用开始使用MongoDB,在2018年的数据库排名中处于第五位,并且在今年1月份受欢迎程度排在第二位,成为最受欢迎的NoSQL数据库 ...

  3. Java基础-SSM之mybatis快速入门篇

    Java基础-SSM之mybatis快速入门篇 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 其实你可能会问什么是SSM,简单的说就是spring mvc + Spring + m ...

  4. 服务器搭建快速入门——适用于Android应用服务器、微信小程序服务器(一)

    目录 服务器搭建快速入门--适用于Android应用服务器.微信小程序服务器 适用人群 使用方案 准备工作 硬件方面 软件方面 开始搭建 服务器搭建快速入门--适用于Android应用服务器.微信小程 ...

  5. Java如何快速入门?Java初学者从入门到精通必看!

            作为刚刚接触Java的小白来说,最担心的应该就是Java怎么学,都需要掌握哪些内容?今天这篇文章希望能帮助大家快速入门Java,少走弯路! 如何快速入门Java? 一.作为刚接触Jav ...

  6. azure linux 配置端口,快速入门 - 在 Azure 门户中创建 Linux VM - Azure Virtual Machines | Microsoft Docs...

    您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn. 快速入门:在 Azur ...

  7. unformat方法java_快速入门介绍Java中强大的String.format()

    快速入门介绍Java中强大的String.format() 发布于 2020-12-12| 复制链接 摘记: 前言从 Java 5.0 开始,String 类新增了一个强大的字符串格式化方法 form ...

  8. python构建知识库_快速入门:创建知识库 - REST、Python - QnA Maker - Azure Cognitive Services | Microsoft Docs...

    您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn. 快速入门:通过 Pyt ...

  9. java redis快速入门_快速入门Redis系列(3)——Redis的JavaAPI操作(附带练习)

    作为快速入门Redis系列的第三篇博客,本篇为大家带来的是Redis的JavaAPI操作. 码字不易,先赞后看! Redis的JavaAPI操作 看完了上一篇博客,相信大家对于Redis的数据类型有了 ...

最新文章

  1. 关系型数据库与NOSQL
  2. 51nod1092(lcs简单运用/dp)
  3. python安装vpython_VPython:一个Python的3D图形动画库+被忽略的数据可视化功能
  4. 微软Azure AspNetCore微服务实战第2期(内附PPT下载)
  5. Scrapy爬虫抓取ZOL手机详情
  6. 曼联刷新132年队史纪录
  7. PHP面向对象学习(一)
  8. 去除A和B数组中的交集
  9. Android计算器 (课程设计项目)
  10. 年末总结 | 音视频开发进阶 2021 干货合集
  11. 【线性代数】向量组的线性相关性公式定理速查
  12. 腾讯云数据库 TDSQL—— 私有云安装部署手册
  13. 桌面时间的最佳管理者-软媒时间
  14. 家庭收支记账软件项目【Golang-面向对象】
  15. pytorch骚操作之梯度累加,变相增大batch size
  16. ChatGPT爆火背后的真相:学编程已经成为必选项
  17. NC平台 后台任务配置
  18. 钱都花哪去了?预算费用控制管理系统帮企业精准管理“金脉”
  19. 【Introduction to Artificial Intelligence and Data Analytics】(TBC)
  20. 分群思维(五)特殊的分群思维-同期群分析

热门文章

  1. C++11 std::bind 和 std::placeholder
  2. java报错误设置属性值_java – 设置属性值时出错;嵌套异常是org.springframework.beans.NotWritablePropertyException:...
  3. python 英语词频统计软件_Python数据挖掘——文本分析
  4. 专用计算机例子,计算机基础综合题案例.doc
  5. matlab 二维高斯滤波 傅里叶_光电图像处理 | 傅里叶变换(二)
  6. docker 发布tomcat项目_Docker部署java项目[tomcat环境]
  7. UglifyJs Unexpected token: keyword (const)
  8. mfc 子窗体任何消息都不触发_winform让窗体一直显示在桌面上以及FindWindow
  9. 虚拟机ubuntu19.04下设置idea快捷键
  10. 标准库 - 输入输出处理(input and output facilities) lua