All Products
Search
Document Center

Object Storage Service:Streaming download (Java SDK V1)

Last Updated:Mar 20, 2026

Use streaming download to read object content from OSS in chunks, without loading the entire object into memory. This approach is suitable for downloading large files, processing data in real time, and retrieving data incrementally over a network.

Prerequisites

Before you begin, ensure that you have:

  • An OSS bucket containing the object to download

  • The oss:GetObject permission — for details, see Attach a custom policy to a RAM user

  • The OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables configured with your access credentials

Usage notes

  • The examples on this page use the public endpoint for the China (Hangzhou) region (https://oss-cn-hangzhou.aliyuncs.com). Replace it with the endpoint for your bucket's region. If you access OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. For a full list of endpoints, see OSS regions and endpoints.

  • These examples create an OSSClient instance using an OSS endpoint. To create an instance using a custom domain name or Security Token Service (STS), see Configuration examples for common scenarios.

How it works

Call ossClient.getObject(bucketName, objectName) to get an OSSObject. The object contains the bucket name, object name, object metadata, and an input stream. Call getObjectContent() on the OSSObject to get the input stream, then read data from it in chunks using a byte buffer. After reading, close both the input stream and the OSSObject to avoid connection leaks.

Sample code

Read into a byte array

The following example reads object content into a ByteArrayOutputStream and converts it to a byte array.

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class Stream {
    public static void main(String[] args) throws Exception {
        // Replace with the endpoint for your bucket's region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Credentials are read from environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with your bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Replace with the full object path (excluding the bucket name). Example: exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Replace with the region ID for your bucket. Example: cn-hangzhou.
        String region = "cn-hangzhou";

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Get the object. ossObject contains the bucket name, object name, metadata, and an input stream.
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream inputStream = ossObject.getObjectContent();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // Read the stream in 1 KB chunks.
            byte[] readBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(readBuffer)) != -1) {
                byteArrayOutputStream.write(readBuffer, 0, bytesRead);
            }

            byte[] fileBytes = byteArrayOutputStream.toByteArray();
            System.out.println("Downloaded file size: " + fileBytes.length + " bytes");

            // Close the stream and the object to release the connection.
            // Skipping this step causes connection leaks, which can exhaust available connections.
            inputStream.close();
            byteArrayOutputStream.close();
            ossObject.close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Save to a local file

The following example streams object content directly to a local file using FileOutputStream.

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;

import java.io.*;

public class GetObjectStreamtoLocalFile {
    public static void main(String[] args) throws Exception {
        // Replace with the endpoint for your bucket's region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Credentials are read from environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with your bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Replace with the full object path (excluding the bucket name). Example: exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Replace with the region ID for your bucket. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // Replace with your local file path.
        String localFilePath = "D:\\localpath\\examplefile.txt";

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream inputStream = ossObject.getObjectContent();

            // Write the stream to a local file in 1 KB chunks.
            try (FileOutputStream fileOutputStream = new FileOutputStream(localFilePath)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
                System.out.println("Downloaded file saved to: " + localFilePath);
            }

            // Close the input stream and the object to release the connection.
            inputStream.close();
            ossObject.close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

References