У меня есть CloudBlobContainer, содержащий файл (csv), который я хочу переместить в общий файловый ресурс Azure. В текущем подходе я загружаю файл, хранящийся в контейнере, во временный файл, а затем загружаю тот же временный файл в общий файловый ресурс.
CloudBlockBlobsourceBlob = container.getBlockBlobReference(sourceFilePath);
CloudFile destFile = cloudDir.getFileReference(destFileName);
File tmpCsvFile = Files.createTempFile(destFileName, "")
.toFile();
sourceBlob.downloadToFile(tmpCsvFile.getAbsolutePath().substring(0,
tmpCsvFile.getAbsolutePath().lastIndexOf(File.separator)) + File.separator + destFileName);
destFile.uploadFromFile(tmpCsvFile.getAbsolutePath().substring(0,
tmpCsvFile.getAbsolutePath().lastIndexOf(File.separator)) + File.separator + destFileName);
Мне было интересно, могу ли я напрямую переместить/скопировать файл без необходимости его загрузки, потому что для больших файлов эта часть кода может занять много времени.
Я наткнулся на .startCopy и попытался использовать его, как показано ниже. Детали хранилища, пути/имена файлов такие же, как и в предыдущем подходе.
CloudBlockBlob sourceBlob = container.getBlockBlobReference(sourceFilePath);
CloudFile destFile = cloudDir.getFileReference(destFileName);
if (!destFile.exists()) {
destFile.create(1024);
}
destFile.startCopy(sourceBlob);
С этими изменениями я получаю следующее исключение.
com.microsoft.azure.storage.StorageException: The specified resource does not exist. " at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:89) ~[azure-storage-5.0.0.jar!/:?]" " at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:305) ~[azure-storage-5.0.0.jar!/:?]" " at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:175) ~[azure-storage-5.0.0.jar!/:?]" " at com.microsoft.azure.storage.file.CloudFile.startCopy(CloudFile.java:472) ~[azure-storage-5.0.0.jar!/:?]" " at com.microsoft.azure.storage.file.CloudFile.startCopy(CloudFile.java:362) ~[azure-storage-5.0.0.jar!/:?]" " at com.microsoft.azure.storage.file.CloudFile.startCopy(CloudFile.java:320) ~[azure-storage-5.0.0.jar!/:?]"
🤔 А знаете ли вы, что...
Java поддерживает лямбда-выражения, введенные в Java 8, для более удобной работы с функциями.
Перемещение файла из контейнера BLOB-объектов Azure в общий файловый ресурс Azure в приложении Spring Boot
Вы можете использовать приведенный ниже код, чтобы скопировать файл из хранилища BLOB-объектов Azure в общий файловый ресурс Azure с помощью Java.
Код:
public class App {
public static void main(String[] args) {
String connectionString = "xxxxx";
String sourceContainerName = "test";
String sourceBlobName = "titanic.csv";
String destinationShareName = "share1";
String destinationDirectoryName = "sample";
String destinationFileName = "test.csv";
// Create a BlobServiceClient object to connect to your Azure Storage account
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
.connectionString(connectionString)
.buildClient();
BlobContainerClient sourceContainerClient = blobServiceClient.getBlobContainerClient(sourceContainerName);
ShareFileClient fileClient = new ShareFileClientBuilder().connectionString(connectionString).shareName(destinationShareName).resourcePath(destinationDirectoryName + "/" + destinationFileName).buildFileClient();
BlobClient sourceBlobClient = sourceContainerClient.getBlobClient(sourceBlobName);
String sourceBlobUrl = sourceBlobClient.getBlobUrl();
SyncPoller<ShareFileCopyInfo, Void> poller = fileClient.beginCopy(sourceBlobUrl, (Map<String, String>) null, Duration.ofSeconds(2));
PollResponse<ShareFileCopyInfo> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
return;
}
}
if (pollResponse.getStatus().isComplete() && pollResponse.getStatus() != null) {
ShareFileCopyInfo value = pollResponse.getValue();
System.out.printf("Copy source: %s. Status: %s.%n", value.getCopySourceUrl(), value.getCopyStatus());
} else {
System.out.println("Copy operation failed.");
}
}
}
Зависимость:
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
<version>12.25.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-file-share</artifactId>
<version>12.21.4</version>
</dependency>
Выход:
Copy source: https://venkat123.blob.core.windows.net/test%2Ftitanic.csv. Status: success.
После копирования файла из Azure Blob в общий файловый ресурс вы можете удалить исходный большой двоичный объект.
Портал:
Ссылка: Клиентская библиотека Azure File Share для Java | Microsoft Learn