Java를 사용하여 Azure Data Lake Storage Gen2에서 디렉터리 및 파일 관리

이 문서에서는 Java를 사용하여 계층 구조 네임스페이스가 있는 스토리지 계정에서 디렉터리, 파일 및 사용 권한을 만들고 관리하는 방법을 보여 드립니다.

디렉터리 및 파일의 ACL(액세스 제어 목록)을 가져오거나 설정하고 업데이트하는 방법에 대한 자세한 내용은 Java를 사용한 Azure Data Lake Storage Gen2의 ACL 관리를 참조하세요.

패키지(Maven) | 샘플 | API 참조 | Gen1에서 Gen2로 매핑 | 피드백 제공

필수 구성 요소

프로젝트 설정

시작하려면 이 페이지를 열고 최신 버전의 Java 라이브러리를 찾습니다. 텍스트 편집기에서 pom.xml 파일을 엽니다. 해당 버전을 참조하는 종속성 요소를 추가합니다.

Microsoft Entra ID를 사용하여 클라이언트 애플리케이션을 인증하려는 경우 Azure ID 라이브러리에 종속성을 추가합니다. 자세한 내용은 Java용 Azure Identity 클라이언트 라이브러리를 참조하세요.

그런 다음 이러한 imports 문을 코드 파일에 추가합니다.

import com.azure.identity.*;
import com.azure.storage.common.StorageSharedKeyCredential;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.BinaryData;
import com.azure.storage.file.datalake.*;
import com.azure.storage.file.datalake.models.*;
import com.azure.storage.file.datalake.options.*;

참고 항목

Data Lake Storage의 다중 프로토콜 액세스를 통해 애플리케이션은 Blob API와 Data Lake Storage Gen2 API를 모두 사용하여 HNS(계층 구조 네임스페이스)가 사용하도록 설정된 스토리지 계정의 데이터로 작업할 수 있습니다. 디렉터리 작업 및 ACL과 같은 Data Lake Storage Gen2의 고유한 기능을 사용하는 경우 이 문서에 표시된 대로 Data Lake Storage Gen2 API를 사용합니다.

특정 시나리오에서 사용할 API를 선택할 때 알려진 문제HNS가 워크로드 및 애플리케이션에 미치는 영향과 함께 애플리케이션의 워크로드와 요구 사항을 고려합니다.

액세스 권한 부여 및 데이터 리소스에 연결

이 문서의 코드 예제를 사용하려면 스토리지 계정을 나타내는 권한 있는 DataLakeServiceClient 인스턴스를 만들어야 합니다. Microsoft Entra ID, 계정 액세스 키 또는 SAS(공유 액세스 서명)를 사용하여 DataLakeServiceClient 개체에 권한을 부여할 수 있습니다.

Java용 Azure ID 클라이언트 라이브러리를 사용하여 Microsoft Entra ID로 애플리케이션을 인증할 수 있습니다.

DataLakeServiceClient 인스턴스를 만들고 DefaultAzureCredential 클래스의 새 인스턴스를 전달합니다.

static public DataLakeServiceClient GetDataLakeServiceClient(String accountName){
    DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();

    DataLakeServiceClient dataLakeServiceClient = new DataLakeServiceClientBuilder()
        .endpoint("https://" + accountName + ".dfs.core.windows.net")
        .credential(defaultCredential)
        .buildClient();

    return dataLakeServiceClient;
}

DefaultAzureCredential을 사용하여 데이터에 대한 액세스 권한을 부여하는 방법에 대한 자세한 내용은 Java용 Azure ID 클라이언트 라이브러리를 참조하세요.

컨테이너 만들기

컨테이너는 파일의 파일 시스템 역할을 합니다. 다음 메서드를 사용하여 컨테이너를 만들 수 있습니다.

다음 코드 예제에서는 컨테이너를 만들고 나중에 사용할 DataLakeFileSystemClient 개체를 반환합니다.

public DataLakeFileSystemClient CreateFileSystem(
        DataLakeServiceClient serviceClient,
        String fileSystemName) {

    DataLakeFileSystemClient fileSystemClient = serviceClient.createFileSystem(fileSystemName);

    return fileSystemClient;
}

디렉터리 만들기

다음 메서드를 사용하여 컨테이너에서 디렉터리 참조를 만들 수 있습니다.

다음 코드 예제에서는 디렉터리를 컨테이너에 추가한 다음 하위 디렉터리를 추가하고 나중에 사용할 DataLakeDirectoryClient 개체를 반환합니다.

public DataLakeDirectoryClient CreateDirectory(
        DataLakeFileSystemClient fileSystemClient,
        String directoryName,
        String subDirectoryName) {

    DataLakeDirectoryClient directoryClient = fileSystemClient.createDirectory(directoryName);

    return directoryClient.createSubdirectory(subDirectoryName);
}

디렉터리 이름 바꾸기 또는 이동

다음 메서드를 사용하여 디렉터리의 이름을 바꾸거나 디렉터리를 이동할 수 있습니다.

원하는 디렉터리의 경로를 매개 변수로 전달합니다. 다음 코드 예제에서는 하위 디렉터리의 이름을 바꾸는 방법을 보여 줍니다.

public DataLakeDirectoryClient RenameDirectory(
        DataLakeFileSystemClient fileSystemClient,
        String directoryPath,
        String subdirectoryName,
        String subdirectoryNameNew) {

    DataLakeDirectoryClient directoryClient = fileSystemClient
            .getDirectoryClient(String.join("/", directoryPath, subdirectoryName));

    return directoryClient.rename(
            fileSystemClient.getFileSystemName(),
            String.join("/", directoryPath, subdirectoryNameNew));
}

다음 코드 예제에서는 하위 디렉터리를 한 디렉터리에서 다른 디렉터리로 이동하는 방법을 보여 줍니다.

public DataLakeDirectoryClient MoveDirectory(
        DataLakeFileSystemClient fileSystemClient,
        String directoryPathFrom,
        String directoryPathTo,
        String subdirectoryName) {

    DataLakeDirectoryClient directoryClient = fileSystemClient
            .getDirectoryClient(String.join("/", directoryPathFrom, subdirectoryName));

    return directoryClient.rename(
            fileSystemClient.getFileSystemName(),
            String.join("/", directoryPathTo, subdirectoryName));
}

디렉터리에 파일 업로드

다음 메서드를 사용하여 새 파일 또는 기존 파일에 콘텐츠를 업로드할 수 있습니다.

다음 코드 예제에서는 uploadFromFile 메서드를 사용하여 디렉터리에 로컬 파일을 업로드하는 방법을 보여 줍니다.

public void UploadFile(
        DataLakeDirectoryClient directoryClient,
        String fileName) {

    DataLakeFileClient fileClient = directoryClient.getFileClient(fileName);

    fileClient.uploadFromFile("filePath/sample-file.txt");
}

이 메서드를 사용하여 콘텐츠를 만들고 새 파일에 업로드하거나 overwrite 매개 변수를 true로 설정하여 기존 파일을 덮어쓸 수 있습니다.

파일에 데이터 추가

다음 메서드를 사용하여 파일에 추가할 데이터를 업로드할 수 있습니다.

다음 코드 예제에서는 다음 단계를 사용하여 파일 끝에 데이터를 추가하는 방법을 보여 줍니다.

  • 작업 중인 파일 리소스를 나타내는 DataLakeFileClient 개체를 만듭니다.
  • DataLakeFileClient.append 메서드를 사용하여 파일에 데이터를 업로드합니다.
  • DataLakeFileClient.flush 메서드를 호출해 업로드를 완료하여 이전에 업로드한 데이터를 파일에 씁니다.
public void AppendDataToFile(
        DataLakeDirectoryClient directoryClient) {

    DataLakeFileClient fileClient = directoryClient.getFileClient("sample-file.txt");
    long fileSize = fileClient.getProperties().getFileSize();

    String sampleData = "Data to append to end of file";
    fileClient.append(BinaryData.fromString(sampleData), fileSize);

    fileClient.flush(fileSize + sampleData.length(), true);
}

디렉터리에서 다운로드

다음 코드 예제에서는 다음 단계를 사용하여 디렉터리에서 로컬 파일로 파일을 다운로드하는 방법을 보여 줍니다.

  • 다운로드할 파일을 나타내는 DataLakeFileClient 개체를 만듭니다.
  • DataLakeFileClient.readToFile 메서드를 사용하여 파일을 읽습니다. 이 예제에서는 기존 파일을 덮어쓰는 overwrite 매개 변수를 true로 설정합니다.
public void DownloadFile(
        DataLakeDirectoryClient directoryClient,
        String fileName) {

    DataLakeFileClient fileClient = directoryClient.getFileClient(fileName);

    fileClient.readToFile("filePath/sample-file.txt", true);
}

디렉터리 콘텐츠 나열

다음 메서드를 사용하고 결과를 열거하여 디렉터리 콘텐츠를 나열할 수 있습니다.

결과의 경로를 열거하면 값을 가져오는 동안 서비스에 여러 요청을 할 수 있습니다.

다음 코드 예제에서는 디렉터리에 있는 각 파일의 이름을 인쇄합니다.

public void ListFilesInDirectory(
        DataLakeFileSystemClient fileSystemClient,
        String directoryName) {

    ListPathsOptions options = new ListPathsOptions();
    options.setPath(directoryName);

    PagedIterable<PathItem> pagedIterable = fileSystemClient.listPaths(options, null);

    java.util.Iterator<PathItem> iterator = pagedIterable.iterator();
    PathItem item = iterator.next();

    while (item != null) {
        System.out.println(item.getName());

        if (!iterator.hasNext()) {
            break;
        }
        item = iterator.next();
    }

}

디렉터리 삭제

다음 메서드 중 하나를 사용하여 디렉터리를 삭제할 수 있습니다.

다음 코드 예제에서는 deleteWithResponse를 사용하여 비어 있지 않은 디렉터리와 디렉터리 아래의 모든 경로를 삭제합니다.

public void DeleteDirectory(
        DataLakeFileSystemClient fileSystemClient,
        String directoryName) {

    DataLakeDirectoryClient directoryClient = fileSystemClient.getDirectoryClient(directoryName);

    // Set to true to delete all paths beneath the directory
    boolean recursive = true;

    directoryClient.deleteWithResponse(recursive, null, null, null);
}

참고 항목