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

如何使用适用于 Java v7 的客户端库上传、下载和列出 BlobHow to upload, download, and list blobs using the client library for Java v7

本操作指南介绍如何使用适用于 Java v7 的客户端库上传、下载和列出 Azure Blob 存储容器中的块 Blob。In this how-to guide, you learn how to use the client library for Java v7 to upload, download, and list block blobs in a container in Azure Blob storage.

提示

适用于 Java 的 Azure 存储客户端库的最新版本是 v10。The latest version of the Azure Storage client library for Java is v10. Microsoft 建议尽可能使用最新版本的客户端库。Microsoft recommends that you use the latest version of the client library when possible. 若要开始使用 v10,请参阅快速入门:使用 Java 存储 SDK V10 上传、下载和列出 BlobTo get started using v10, see Quickstart: Upload, download, and list blobs by using the Java Storage SDK V10.

必备组件Prerequisites

如果没有 Azure 订阅,请在开始之前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.

同时在 Azure 门户中创建 Azure 存储帐户。Also create an Azure storage account in the Azure portal. 有关如何创建帐户的帮助,请参阅创建存储帐户For help creating the account, see Create a storage account.

确保满足以下先决条件:Make sure you have the following prerequisites:

  • 安装含有 Maven 集成的 IDE。Install an IDE that has Maven integration.

  • 或者,从命令行安装和配置 Maven。Alternatively, install and configure Maven to work from the command line.

本指南使用具有“适用于 Java 开发者的 Eclipse IDE”配置的 EclipseThis 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 字符串中的 accountnameaccountkeyOnce the project finishes 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:

  1. 导航到 Azure 门户Navigate 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

在应用程序中,必须为存储帐户提供连接字符串。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=<account-name>;" +
"AccountKey=<account-key>";

运行示例Run the sample

此示例应用程序在默认目录(对于 Windows 用户,为 C:\Users<user>\AppData\Local\Temp)中创建一个测试文件,将其上传到 Blob 存储,列出容器中的 Blob,然后下载具有新名称的文件,以便比较旧文件和新文件。This sample application creates a test file in your default directory (C:\Users<user>\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:javaThen 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\<user>\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<user>\AppData\Local\Temp),再继续操作。Before you continue, check your default directory (C:\Users<user>\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 finish 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.

  • 创建指向存储帐户的 CloudStorageAccount 对象的实例。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. 有关容器的详细信息,请参阅命名和引用容器、Blob 和元数据For more information about containers, see Naming and Referencing Containers, Blobs, and Metadata.

创建容器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. 在生产环境中,应用程序从头至尾都使用相同的容器,因此建议仅调用一次 CreateIfNotExistsIn 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());

有多个可以与 Blob 存储配合使用的 upload 方法,其中包括 uploaduploadBlockuploadFullBlobuploadStandardBlobTieruploadTextThere 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

可以使用 CloudBlobContainer.ListBlobs 获取容器中的文件列表。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

使用 CloudBlob.DownloadToFile 将 blob 下载到本地磁盘。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

如果不再需要上传的 Blob,可使用 CloudBlobContainer.DeleteIfExists 删除整个容器。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.