Search code examples
azureazure-blob-storageazure-java-sdkazure-sdk-for-java

Nothing read from Azure Blob storage after downloading file in stream data


I'm fetching file from Azure blob storage with the following code but downloadedData is always empty string. I referred this MS document to read the file from the location. The file is not empty and does contain values. I tried with multiple type of files - text,pdf etc. But for all downloadedData is empty. How can I fix this issue?

      BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("abc/file1.txt");
            ByteArrayOutputStream downloadData = new ByteArrayOutputStream();

            blobAsyncClient.downloadStream().subscribe(piece -> {
                try {
                    downloadData.write(piece.array());
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            });

Solution

  • The issue is because you're calling an Async method, but not awaiting for the completion.

    You can call the .blockLast() method, or use the doOnComplete().

    blobAsyncClient.downloadStream().subscribe(piece -> {
        try {
            downloadData.write(piece.array());
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }).blockLast();
    

    or

    blobAsyncClient.downloadStream().doOnNext(piece -> {
        try {
            downloadData.write(piece.array());
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }).doOnComplete(() -> {
        // This ensures that the downloadData is not accessed until it's fully populated
    }).subscribe();