다음을 통해 공유


Java 버전 8 클라이언트 라이브러리를 사용하는 Azure 파일 공유 코드 샘플

이 문서에서는 Java용 Azure 파일 공유 클라이언트 라이브러리의 버전 8을 사용하는 코드 샘플을 보여 줍니다.

2023년 3월 31일부터 현재 Azure SDK 지침을 준수하지 않는 Azure SDK 라이브러리에 대한 지원이 중지되었습니다. 새로운 Azure SDK 라이브러리는 일관된 환경을 구동하고 보안 태세를 강화하기 위해 정기적으로 업데이트됩니다. 새 기능과 중요한 보안 업데이트를 활용하기 위해 새 Azure SDK 라이브러리로 전환하는 것이 좋습니다.

이전 라이브러리는 2023년 3월 31일 이후에도 계속 사용할 수 있지만 더 이상 Microsoft의 공식 지원 및 업데이트를 받지 않습니다. 자세한 내용은 사용 중지 공지 지원을 참조하세요.

필수 조건

Azure 파일 공유 클라이언트 라이브러리를 사용하려면 다음 import 지시문을 추가합니다.

// Include the following imports to use Azure Files APIs v11
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.file.*;

Azure 파일 공유에 액세스

관련 문서: Java를 사용하여 Azure Files 개발

스토리지 계정에 연결하려면 CloudStorageAccount 개체를 사용하여 연결 문자열을 구문 분석 메서드로 전달합니다.

// Use the CloudStorageAccount object to connect to your storage account
try {
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
} catch (InvalidKeyException invalidKey) {
    // Handle the exception
}

CloudStorageAccount.parse 는 InvalidKeyException을 발생시키므로 try/catch 블록 안에 넣어야 합니다.

파일 공유 만들기

관련 문서: Java를 사용하여 Azure Files 개발

Azure Files의 모든 파일과 디렉터리는 공유라고 하는 컨테이너에 저장됩니다.

공유 및 해당 콘텐츠에 대한 액세스 권한을 가져오려면 Azure Files 클라이언트를 만듭니다. 다음 코드 예제에서는 파일 공유를 만드는 방법을 보여 줍니다.

// Create the Azure Files client.
CloudFileClient fileClient = storageAccount.createCloudFileClient();

Azure Files 클라이언트를 사용하면 공유에 대한 참조를 가져올 수 있습니다.

// Get a reference to the file share
CloudFileShare share = fileClient.getShareReference("sampleshare");

실제로 공유를 만들려면 CloudFileShare 개체의 createIfNotExists 메서드를 사용합니다.

if (share.createIfNotExists()) {
    System.out.println("New share created");
}

이때 공유샘플 공유라는 공유에 대한 참조를 저장합니다.

파일 공유 삭제

관련 문서: Java를 사용하여 Azure Files 개발

다음 샘플 코드에서는 파일 공유를 삭제합니다.

CloudFileShare 개체에서 deleteIfExists 메서드를 호출하여 공유를 삭제합니다.

try
{
    // Retrieve storage account from connection-string.
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

    // Create the file client.
   CloudFileClient fileClient = storageAccount.createCloudFileClient();

   // Get a reference to the file share
   CloudFileShare share = fileClient.getShareReference("sampleshare");

   if (share.deleteIfExists()) {
       System.out.println("sampleshare deleted");
   }
} catch (Exception e) {
    e.printStackTrace();
}

디렉터리 만들기

관련 문서: Java를 사용하여 Azure Files 개발

루트 디렉터리에 이들 모두를 포함하는 대신 하위 디렉터리 내에서 파일을 배치하여 스토리지를 구성할 수 있습니다.

다음 코드에서는 루트 디렉터리 아래에 sampledir라는 하위 디렉터리를 만듭니다.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

//Get a reference to the sampledir directory
CloudFileDirectory sampleDir = rootDir.getDirectoryReference("sampledir");

if (sampleDir.createIfNotExists()) {
    System.out.println("sampledir created");
} else {
    System.out.println("sampledir already exists");
}

디렉터리 삭제

관련 문서: Java를 사용하여 Azure Files 개발

다음 코드 예제에서는 디렉터리를 삭제하는 방법을 보여 줍니다. 여전히 파일이나 하위 디렉터리가 포함된 디렉터리를 삭제할 수 없습니다.

// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

// Get a reference to the directory you want to delete
CloudFileDirectory containerDir = rootDir.getDirectoryReference("sampledir");

// Delete the directory
if ( containerDir.deleteIfExists() ) {
    System.out.println("Directory deleted");
}

Azure 파일 공유의 파일 및 디렉터리 열거

관련 문서: Java를 사용하여 Azure Files 개발

CloudFileDirectory 참조에서 listFilesAndDirectories를 호출하여 파일과 디렉터리의 목록을 가져옵니다. 메서드는 반복할 수 있는 ListFileItem 개체 목록을 반환합니다.

다음 코드에서는 루트 디렉터리에 있는 파일과 디렉터리를 나열합니다.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

for ( ListFileItem fileItem : rootDir.listFilesAndDirectories() ) {
    System.out.println(fileItem.getUri());
}

파일 업로드

관련 문서: Java를 사용하여 Azure Files 개발

공유 개체에서 getRootDirectoryReference 메서드를 호출하여 파일을 업로드할 디렉터리에 대한 참조를 가져옵니다.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

이제 공유의 루트 디렉터리에 대한 참조를 가졌으므로 다음 코드를 사용하여 파일을 업로드할 수 있습니다.

// Define the path to a local file.
final String filePath = "C:\\temp\\Readme.txt";

CloudFile cloudFile = rootDir.getFileReference("Readme.txt");
cloudFile.uploadFromFile(filePath);

파일 다운로드

관련 문서: Java를 사용하여 Azure Files 개발

다음 예제에서는 SampleFile.txt를 다운로드하고 해당 콘텐츠를 표시합니다.

//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

//Get a reference to the directory that contains the file
CloudFileDirectory sampleDir = rootDir.getDirectoryReference("sampledir");

//Get a reference to the file you want to download
CloudFile file = sampleDir.getFileReference("SampleFile.txt");

//Write the contents of the file to the console.
System.out.println(file.downloadText());

파일 삭제

관련 문서: Java를 사용하여 Azure Files 개발

다음 코드는 sampledir라는 이름의 디렉터리 안에 저장된 SampleFile.txt라는 이름의 파일을 삭제합니다.

// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();

// Get a reference to the directory where the file to be deleted is in
CloudFileDirectory containerDir = rootDir.getDirectoryReference("sampledir");

String filename = "SampleFile.txt"
CloudFile file;

file = containerDir.getFileReference(filename)
if ( file.deleteIfExists() ) {
    System.out.println(filename + " was deleted");
}