See: Description
Package | Description |
---|---|
com.azure.storage.file.share |
This package contains the classes to perform actions on Azure Storage File.
|
com.azure.storage.file.share.models |
Package containing classes for AzureFileStorage.
|
com.azure.storage.file.share.options |
Package containing options model classes used by Azure Storage File Shares.
|
com.azure.storage.file.share.sas |
Package containing SAS (shared access signature) classes used by Azure Storage File Shares.
|
com.azure.storage.file.share.specialized |
Package containing specialized clients for Azure Storage Files.
|
The Server Message Block (SMB) protocol is the preferred file share protocol used on-premises today. The Microsoft Azure File Share service enables customers to leverage the availability and scalability of Azure's Cloud Infrastructure as a Service (IaaS) SMB without having to rewrite SMB client applications.
Files stored in Azure File Share service shares are accessible via the SMB protocol, and also via REST APIs. The File Share service offers the following four resources: the storage account, shares, directories, and files. Shares provide a way to organize sets of files and also can be mounted as an SMB file share that is hosted in the cloud.
Source code | API reference documentation | REST API documentation | Product documentation | Samples
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-file-share</artifactId>
<version>12.7.0</version>
</dependency>
To create a Storage Account you can use the Azure Portal or Azure CLI.
az storage account create \
--resource-group <resource-group-name> \
--name <storage-account-name> \
--location <location>
In order to interact with the Storage service (File Share Service, Share, Directory, MessageId, File) you'll need to create an instance of the Service Client class. To make this possible you'll need the Account SAS (shared access signature) string of Storage account. Learn more at SAS Token
SAS Token
Use the Azure CLI snippet below to get the SAS token from the Storage account.
az storage file generate-sas
--name {account name}
--expiry {date/time to expire SAS token}
--permission {permission to grant}
--connection-string {connection string of the storage account}
CONNECTION_STRING=<connection-string>
az storage file generate-sas
--name javasdksas
--expiry 2019-06-05
--permission rpau
--connection-string $CONNECTION_STRING
Alternatively, get the Account SAS Token from the Azure Portal.
Shared Key Credential
File Shares are addressable using the following URL format:
https://<storage account>.file.core.windows.net/<share>
The following URL addresses a queue in the diagram:
https://myaccount.file.core.windows.net/images-to-download
For the storage account, the base URI for queue operations includes the name of the account only:
https://myaccount.file.core.windows.net
For file, the base URI includes the name of the account and the name of the directory/file:
https://myaccount.file.core.windows.net/myshare/mydirectorypath/myfile
Uses the shareServiceClient
generated from shareSeviceClient section below.
try {
shareServiceClient.createShare("myShare");
} catch (ShareStorageException e) {
logger.error("Failed to create a share with error code: " + e.getErrorCode());
}
The URI to reference a share, directory or file must be unique. Within a given storage account, every share must have a unique name. Every file within a given share or directory must also have a unique name within that share or directory.
If you attempt to create a share, directory, or file with a name that violates naming rules, the request will fail with status code 400 (Bad Request).
The rules for File Share service names are more restrictive than what is prescribed by the SMB protocol for SMB share names, so that the Blob and File services can share similar naming conventions for containers and shares. The naming restrictions for shares are as follows:
The Azure File Share service naming rules for directory and file names are as follows:
" \ / : | < > * ?
Metadata for a share or file resource is stored as name-value pairs associated with the resource. Directories do not have metadata. Metadata names must adhere to the naming rules for C# identifiers.
Note that metadata names preserve the case with which they were created, but are case-insensitive when set or read. If two or more metadata headers with the same name are submitted for a resource, the Azure File service returns status code 400 (Bad Request).
The File Share Service REST API provides operations on accounts and manage file service properties. It allows the operations of listing and deleting shares, getting and setting file service properties.
Once you have the SASToken, you can construct the shareServiceClient
with ${accountName}
, ${sasToken}
String shareServiceURL = String.format("https://%s.file.core.windows.net", ACCOUNT_NAME);
ShareServiceClient shareServiceClient = new ShareServiceClientBuilder().endpoint(shareServiceURL)
.sasToken(SAS_TOKEN).buildClient();
The share resource includes metadata and properties for that share. It allows the opertions of creating, creating snapshot, deleting shares, getting share properties, setting metadata, getting and setting ACL (Access policy).
Once you have the SASToken, you can construct the file service client with ${accountName}
, ${shareName}
, ${sasToken}
String shareURL = String.format("https://%s.file.core.windows.net", ACCOUNT_NAME);
ShareClient shareClient = new ShareClientBuilder().endpoint(shareURL)
.sasToken(SAS_TOKEN).shareName(shareName).buildClient();
The directory resource includes the properties for that directory. It allows the operations of creating, listing, deleting directories or subdirectories or files, getting properties, setting metadata, listing and force closing the handles.
Once you have the SASToken, you can construct the file service client with ${accountName}
, ${shareName}
, ${directoryPath}
, ${sasToken}
String directoryURL = String.format("https://%s.file.core.windows.net", ACCOUNT_NAME);
ShareDirectoryClient directoryClient = new ShareFileClientBuilder().endpoint(directoryURL)
.sasToken(SAS_TOKEN).shareName(shareName).resourcePath(directoryPath).buildDirectoryClient();
The file resource includes the properties for that file. It allows the operations of creating, uploading, copying, downloading, deleting files or range of the files, getting properties, setting metadata, listing and force closing the handles.
Once you have the SASToken, you can construct the file service client with ${accountName}
, ${shareName}
, ${directoryPath}
, ${fileName}
, ${sasToken}
String fileURL = String.format("https://%s.file.core.windows.net", ACCOUNT_NAME);
ShareFileClient fileClient = new ShareFileClientBuilder().connectionString(CONNECTION_STRING)
.endpoint(fileURL).shareName(shareName).resourcePath(directoryPath + "/" + fileName).buildFileClient();
The following sections provide several code snippets covering some of the most common Configuration Service tasks, including: - Create a Share - Create a snapshot on Share - Create a Directory - Create a Subdirectory - Create a File - List all Shares - List all Subdirectories and Files - List all ranges on file - Delete a Share - Delete a Directory - Delete a Subdirectory - Delete a File - Copy a File - Abort copy a File - Upload data to Storage File - Upload file to Storage File - Download data from file range - Download file from Storage File - Get a share service properties - Set a share service properties - Set a Share metadata - Get a Share access policy - Set a Share access policy - Get handles on Directory and File - Force close handles on handle id - Set quota on Share - Set file httpHeaders
Create a share in the Storage Account. Throws StorageException If the share fails to be created.
Taking a ShareServiceClient in KeyConcept, ${shareServiceClient}
.
String shareName = "testshare";
shareServiceClient.createShare(shareName);
Taking a ShareServiceClient in KeyConcept, ${shareServiceClient}
.
String shareName = "testshare";
ShareClient shareClient = shareServiceClient.getShareClient(shareName);
shareClient.createSnapshot();
Taking the ${shareClient}
initialized above, ${shareClient}
.
String dirName = "testdir";
shareClient.createDirectory(dirName);
Taking the directoryClient in KeyConcept, ${directoryClient}
.
String subDirName = "testsubdir";
directoryClient.createSubdirectory(subDirName);
Taking the directoryClient in KeyConcept, ${directoryClient}
.
String fileName = "testfile";
long maxSize = 1024;
directoryClient.createFile(fileName, maxSize);
Taking the shareServiceClient in KeyConcept, ${shareServiceClient}
shareServiceClient.listShares();
Taking the directoryClient in KeyConcept, ${directoryClient}
directoryClient.listFilesAndDirectories();
Taking the fileClient in KeyConcept, ${fileClient}
fileClient.listRanges();
Taking the shareClient in KeyConcept, ${shareClient}
shareClient.delete();
Taking the shareClient in KeyConcept, ${shareClient}
.
String dirName = "testdir";
shareClient.deleteDirectory(dirName);
Taking the directoryClient in KeyConcept, ${directoryClient}
.
String subDirName = "testsubdir";
directoryClient.deleteSubdirectory(subDirName);
Taking the directoryClient in KeyConcept, ${directoryClient}
.
String fileName = "testfile";
directoryClient.deleteFile(fileName);
Taking the fileClient in KeyConcept, ${fileClient}
with string of source URL.
String sourceURL = "https://myaccount.file.core.windows.net/myshare/myfile";
Duration pollInterval = Duration.ofSeconds(2);
SyncPoller<ShareFileCopyInfo, Void> poller = fileClient.beginCopy(sourceURL, null, pollInterval);
Taking the fileClient in KeyConcept, ${fileClient}
with the copy info response returned above ${copyId}=[copyInfoResponse](#copy-a-file)
.
fileClient.abortCopy("copyId");
Taking the fileClient in KeyConcept, ${fileClient}
with data of "default" .
String uploadText = "default";
InputStream data = new ByteArrayInputStream(uploadText.getBytes(StandardCharsets.UTF_8));
fileClient.upload(data, uploadText.length());
Taking the fileClient in KeyConcept, ${fileClient}
.
String filePath = "${myLocalFilePath}";
fileClient.uploadFromFile(filePath);
Taking the fileClient in KeyConcept, ${fileClient}
with the range from 1024 to 2048.
ShareFileRange fileRange = new ShareFileRange(0L, 2048L);
OutputStream stream = new ByteArrayOutputStream();
fileClient.downloadWithResponse(stream, fileRange, false, null, Context.NONE);
Taking the fileClient in KeyConcept, ${fileClient}
and download to the file of filePath.
String filePath = "${myLocalFilePath}";
fileClient.downloadToFile(filePath);
Taking a ShareServiceClient in KeyConcept, ${shareServiceClient}
.
shareServiceClient.getProperties();
Taking a ShareServiceClient in KeyConcept, ${shareServiceClient}
.
ShareServiceProperties properties = shareServiceClient.getProperties();
properties.getMinuteMetrics().setEnabled(true).setIncludeApis(true);
properties.getHourMetrics().setEnabled(true).setIncludeApis(true);
shareServiceClient.setProperties(properties);
Taking the shareClient in KeyConcept, ${shareClient}
.
Map<String, String> metadata = Collections.singletonMap("directory", "metadata");
shareClient.setMetadata(metadata);
Taking the shareClient in KeyConcept, ${shareClient}
shareClient.getAccessPolicy();
Taking the shareClient in KeyConcept, ${shareClient}
.
ShareAccessPolicy accessPolicy = new ShareAccessPolicy().setPermissions("r")
.setStartsOn(OffsetDateTime.now(ZoneOffset.UTC))
.setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10));
ShareSignedIdentifier permission = new ShareSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy);
shareClient.setAccessPolicy(Collections.singletonList(permission));
Taking the directoryClient in KeyConcept, ${directoryClient}
PagedIterable<HandleItem> handleItems = directoryClient.listHandles(null, true, Duration.ofSeconds(30), Context.NONE);
Taking the directoryClient in KeyConcept, ${directoryClient}
and the handle id returned above ${handleId}=[handleItems](#get-handles-on-directory-file)
String handleId = handleItems.iterator().next().getHandleId();
directoryClient.forceCloseHandleWithResponse(handleId, Duration.ofSeconds(30), Context.NONE);
Taking the shareClient in KeyConcept, ${shareClient}
.
int quotaOnGB = 1;
shareClient.setQuota(quotaOnGB);
Taking the fileClient in KeyConcept, ${fileClient}
.
ShareFileHttpHeaders httpHeaders = new ShareFileHttpHeaders().setContentType("text/plain");
fileClient.setProperties(1024, httpHeaders, null, null);
When you interact with file using this Java client library, errors returned by the service correspond to the same HTTP status codes returned for REST API requests. For example, if you try to retrieve a share that doesn't exist in your Storage Account, a 404
error is returned, indicating Not Found
.
All client libraries by default use the Netty HTTP client. Adding the above dependency will automatically configure the client library to use the Netty HTTP client. Configuring or changing the HTTP client is detailed in the HTTP clients wiki.
All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an uber jar containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the performance tuning section of the wiki.
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.
If you would like to become an active contributor to this project please follow the instructions provided in Microsoft Azure Projects Contribution Guidelines.
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)
Copyright © 2020 Microsoft Corporation. All rights reserved.