java azure blob 查询_快速入门:适用于 Java 的 Azure Blob 存储客户端库 v8 | Microsoft Docs...
您現在訪問的是微軟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.
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的java azure blob 查询_快速入门:适用于 Java 的 Azure Blob 存储客户端库 v8 | Microsoft Docs...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 形容老师讲课很精彩的词语(形容老师)
- 下一篇: 黑客对吉普牌汽车的攻击途径不包括哪些