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

本快速入门介绍如何使用 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, and you'll create and delete containers.

其他资源:Additional resources:

先决条件Prerequisites

备注

本文中所述的功能现在可用于具有分层命名空间的帐户。The features described in this article are now available to accounts that have a hierarchical namespace. 若要查看限制,请参阅 Azure Data Lake Storage Gen2 中可用的 Blob 存储功能一文。To review limitations, see the Blob storage features available in Azure Data Lake Storage Gen2 article.

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 Java 的 Azure Blob 存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Blob storage client library v12 for Java.

创建项目Create the project

创建名为 blob-quickstart-v12 的 Java 应用程序。Create a Java application named blob-quickstart-v12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 Maven 创建名为 blob-quickstart-v12 的新控制台应用。In a console window (such as cmd, PowerShell, or Bash), use Maven to create a new console app with the name blob-quickstart-v12. 键入以下“mvn”命令,创建“Hello World!”Type the following mvn command to create a "Hello world!" Java 项目。Java project.

    mvn archetype:generate -DgroupId=com.blobs.quickstart \
                           -DartifactId=blob-quickstart-v12 \
                           -DarchetypeArtifactId=maven-archetype-quickstart \
                           -DarchetypeVersion=1.4 \
                           -DinteractiveMode=false
    
  2. 生成项目的输出应如下所示:The output from generating the project should look something like this:

    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------< org.apache.maven:standalone-pom >-------------------
    [INFO] Building Maven Stub Project (No POM) 1
    [INFO] --------------------------------[ pom ]---------------------------------
    [INFO]
    [INFO] >>> maven-archetype-plugin:3.1.2:generate (default-cli) > generate-sources @ standalone-pom >>>
    [INFO]
    [INFO] <<< maven-archetype-plugin:3.1.2:generate (default-cli) < generate-sources @ standalone-pom <<<
    [INFO]
    [INFO]
    [INFO] --- maven-archetype-plugin:3.1.2:generate (default-cli) @ standalone-pom ---
    [INFO] Generating project in Batch mode
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.blobs.quickstart
    [INFO] Parameter: artifactId, Value: blob-quickstart-v12
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.blobs.quickstart
    [INFO] Parameter: packageInPathFormat, Value: com/blobs/quickstart
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.blobs.quickstart
    [INFO] Parameter: groupId, Value: com.blobs.quickstart
    [INFO] Parameter: artifactId, Value: blob-quickstart-v12
    [INFO] Project created from Archetype in dir: C:\QuickStarts\blob-quickstart-v12
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  7.056 s
    [INFO] Finished at: 2019-10-23T11:09:21-07:00
    [INFO] ------------------------------------------------------------------------
        ```
    
    
  3. Switch to the newly created blob-quickstart-v12 folder.

    cd blob-quickstart-v12
    
  4. 在 blob-quickstart-v12 目录中,创建名为 data 的另一个目录。In side the blob-quickstart-v12 directory, create another directory called data. 将在这里创建和存储 blob 数据文件。This is where the blob data files will be created and stored.

    mkdir data
    

安装包Install the package

在文本编辑器中打开 pom.xml 文件。Open the pom.xml file in your text editor. 将以下依赖项元素添加到依赖项组。Add the following dependency element to the group of dependencies.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>12.6.0</version>
</dependency>

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 导航到 /src/main/java/com/blobs/quickstart 目录Navigate to the /src/main/java/com/blobs/quickstart directory
  2. 在编辑器中打开 App.java 文件Open the App.java file in your editor
  3. 删除 System.out.println("Hello world!"); 语句Delete the System.out.println("Hello world!"); statement
  4. 添加 import 指令Add import directives

代码如下:Here's the code:

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
    {
    }
}

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

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

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

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 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.

  4. 找到“密钥 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.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

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

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure Blob 存储最适合存储巨量的非结构化数据。Azure Blob storage is optimized for storing massive amounts of unstructured data. 非结构化数据是不遵循特定数据模型或定义的数据(如文本或二进制数据)。Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data. Blob 存储提供了三种类型的资源:Blob storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的容器A container in the storage account
  • 容器中的 blobA blob in the container

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

Blob 存储体系结构的图示

使用以下 Java 类与这些资源进行交互:Use the following Java classes to interact with these resources:

  • BlobServiceClientBlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers. 存储帐户为 Blob 服务提供顶级命名空间。The storage account provides the top-level namespace for the Blob service.
  • BlobServiceClientBuilderBlobServiceClientBuilder 类提供流畅的生成器 API,以帮助对 BlobServiceClient 对象的配置和实例化。BlobServiceClientBuilder: The BlobServiceClientBuilder class provides a fluent builder API to help aid the configuration and instantiation of BlobServiceClient objects.
  • BlobContainerClientBlobContainerClient 类可用于操纵 Azure 存储容器及其 blob。BlobContainerClient: The BlobContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClientBlobClient 类可用于操纵 Azure 存储 blob。BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.
  • BlobItemBlobItem 类表示从对 listBlobs 的调用返回的单个 blob。BlobItem: The BlobItem class represents individual blobs returned from a call to listBlobs.

代码示例Code examples

这些示例代码片段演示如何使用适用于 Java 的 Azure Blob 存储客户端库执行以下步骤:These example code snippets show you how to perform the following with the Azure Blob storage client library for Java:

获取连接字符串Get the connection string

下面的代码从配置存储连接字符串部分中创建的环境变量中检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

Main 方法内添加此代码:Add this code inside the Main method:

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 = System.getenv("AZURE_STORAGE_CONNECTION_STRING");

创建容器Create a container

确定新容器的名称。Decide on a name for the new container. 以下代码将 UUID 值追加到容器名称,确保其是唯一的。The code below appends a UUID value to the container name to ensure that it is unique.

重要

容器名称必须为小写。Container names must be lowercase. 有关命名容器和 Blob 的详细信息,请参阅命名和引用容器、Blob 和元数据For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

接下来,创建 BlobContainerClient 类,然后调用 create 方法,在存储帐户中实际创建容器。Next, create an instance of the BlobContainerClient class, then call the create method to actually create the container in your storage account.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// 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);

将 blob 上传到容器中Upload blobs to a container

以下代码片段:The following code snippet:

  1. 在本地 data 目录中创建文本文件。Creates a text file in the local data directory.
  2. 对在创建容器部分创建的容器调用 getBlobClient 方法,获取对 BlobClient 对象的引用。Gets a reference to a BlobClient object by calling the getBlobClient method on the container from the Create a container section.
  3. 通过调用 uploadFromFile 方法将本地文本文件上传到 blob。Uploads the local text file to the blob by calling the uploadFromFile method. 此方法将创建 Blob(如果该 Blob 尚不存在),但不会覆盖 Blob(如果该 Blob 已存在)。This method creates the blob if it doesn't already exist, but will not overwrite it if it does.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// 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);

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

通过调用 listBlobs 方法,列出容器中的 blob。List the blobs in the container by calling the listBlobs method. 在这种情况下,只向容器添加了一个 blob,因此列表操作只返回那个 blob。In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

System.out.println("\nListing blobs...");

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

下载 BlobDownload blobs

通过调用 downloadToFile 方法,下载以前创建的 blob。Download the previously created blob by calling the downloadToFile method. 示例代码将向文件名添加后缀“DOWNLOAD”,这样你就可以在本地文件系统中看到这两个文件。The example code adds a suffix of "DOWNLOAD" to the file name so that you can see both files in local file system.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// 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);

删除容器Delete a container

以下代码使用 delete 方法删除整个容器,从而清除该应用所创建的资源。The following code cleans up the resources the app created by removing the entire container using the delete method. 它还会删除由应用创建的本地文件。It also deletes the local files created by the app.

在删除 blob、容器和本地文件之前,应用会调用 System.console().readLine() 以暂停并等待用户输入。The app pauses for user input by calling System.console().readLine() before it deletes the blob, container, and local files. 可以通过此机会验证是否已正确创建资源,然后再删除这些资源。This is a good chance to verify that the resources were created correctly, before they are deleted.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// 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");

运行代码Run the code

此应用在本地文件夹中创建测试文件,并将其上传到 Blob 存储。This app creates a test file in your local folder and uploads it to Blob storage. 然后,该示例会列出容器中的 blob,并使用新名称下载文件,这样便可对新旧文件进行对比。The example then lists the blobs in the container and downloads the file with a new name so that you can compare the old and new files.

导航到包含 pom.xml 文件的目录,并使用以下 mvn 命令编译该项目。Navigate to the directory containing the pom.xml file and compile the project by using the following mvn command.

mvn compile

然后,生成包。Then, build the package.

mvn package

运行以下 mvn 命令以执行应用。Run the following mvn command to execute the app.

mvn exec:java -Dexec.mainClass="com.blobs.quickstart.App" -Dexec.cleanupDaemonThreads=false

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Blob storage v12 - Java quickstart sample

Uploading to Blob storage as blob:
        https://mystorageacct.blob.core.chinacloudapi.cn/quickstartblobsf9aa68a5-260e-47e6-bea2-2dcfcfa1fd9a/quickstarta9c3a53e-ae9d-4863-8b34-f3d807992d65.txt

Listing blobs...
        quickstarta9c3a53e-ae9d-4863-8b34-f3d807992d65.txt

Downloading blob to
        ./data/quickstarta9c3a53e-ae9d-4863-8b34-f3d807992d65DOWNLOAD.txt

Press the Enter key to begin clean up

Deleting blob container...
Deleting the local source and downloaded files...
Done

在开始清理过程之前,请在“data”文件夹中查看这两个文件。Before you begin the clean up process, check your data folder for the two files. 可以打开它们,然后就会观察到它们完全相同。You can open them and observe that they are identical.

验证文件后,按 Enter 键以删除测试文件并完成演示。After you've verified the files, press the Enter key to delete the test files and finish the demo.

后续步骤Next steps

本快速入门介绍了如何使用 Java 上传、下载和列出 blob。In this quickstart, you learned how to upload, download, and list blobs using Java.

若要查看 Blob 存储示例应用,请继续执行以下操作:To see Blob storage sample apps, continue to: