快速入門:使用 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 `
        --define interactiveMode=n `
        --define groupId=com.blobs.quickstart `
        --define artifactId=blob-quickstart-v12 `
        --define archetypeArtifactId=maven-archetype-quickstart `
        --define archetypeVersion=1.4
    
  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.
  • 類別會提供 Fluent 產生器 API,協助設定和具現化 物件。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.
  • [ 類別可讓您操作 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,若已存在,則不會加以覆寫。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.windows.net/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: