All Products
Search
Document Center

Object Storage Service:Get started with OSS SDK for Java

Last Updated:Dec 28, 2024

Object Storage Service (OSS) SDK for Java allows you to easily integrate OSS storage management and data access capabilities into your Java applications. This topic describes how to perform common bucket and object management operations by using OSS SDK for Java, including creating and deleting buckets, and uploading, downloading, listing, and deleting objects.

Prerequisites

Configure environment variables

Configure environment variables for the AccessKey pair.

Linux

  1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Run the following command to apply the changes:

    source ~/.bashrc
  3. Run the following commands to check whether the environment variables take effect:

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Run the following command in the terminal to view the default shell type:

    echo $SHELL
  2. Configure environment variables based on the default shell type.

    Zsh

    1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Run the following command to apply the changes:

      source ~/.zshrc
    3. Run the following commands to check whether the environment variables take effect:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    Bash

    1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. Run the following command to apply the changes:

      source ~/.bash_profile
    3. Run the following commands to check whether the environment variables take effect:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Run the following commands in CMD:

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Run the following commands to check whether the environment variables take effect:

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. Run the following commands in PowerShell:

    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Run the following commands to check whether the environment variable takes effect:

    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Install the SDK

  1. Install Java 7 or later.

    You can check your Java version by running the following command:

    java -version

    If Java is not installed in your environment or the Java version is earlier than V7, download a compatible Java version.

  2. Install OSS SDK for Java.

    Note

    Select an appropriate version of OSS SDK for Java based on your requirements. We recommend that you use the latest version.

    Add dependencies to your Maven project (recommended)

    To use OSS SDK for Java in Java 7 or 8, add the corresponding SDK dependency to the pom.xml file. In this example, the dependency for OSS SDK for Java V3.17.4 is added.

    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>3.17.4</version>
    </dependency>

    If you use Java 9 or later, add the following jaxb-related dependencies in addition to the OSS SDK dependency:

    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <!-- no more than 2.3.3-->
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.3</version>
    </dependency>

    Import the JAR file to an Eclipse project

    To use OSS SDK for Java V3.17.4, perform the following steps to import the JAR file to your project:

    1. Download the OSS SDK for Java package.zip.

    2. Decompress the package.

    3. Copy the aliyun-sdk-oss-3.17.4.jar file and all files in the lib directory to your project.

    4. In Eclipse, select your project and choose Properties > Java Build Path > Add JARs in the right-click menu.

    5. Select all JAR files that you copied and import the files to Libraries.

    Import the JAR files to an IntelliJ IDEA project

    To use OSS SDK for Java V3.17.4, perform the following steps to import the JAR file to your project:

    1. Download the .

    2. Decompress the package.

    3. Copy the aliyun-sdk-oss-3.17.4.jar file and all JAR files in the lib directory to your project.

    4. In IntelliJ IDEA, select your project and choose File > Project Structure > Modules > Dependencies > + > JARs or directories.

    5. Select all JAR files that you copied and import the files to External Libraries.

Example

The following sample code shows how to create and delete a bucket, and upload, download, list, and delete objects by using OSS SDK for Java.

import java.io.*;
import java.util.Random;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;

public class OssJavaSdkQuickStart {
    /** Generate a unique bucket name.*/
    public static String generateUniqueBucketName(String prefix) {
        // Obtain the current timestamp.
        String timestamp = String.valueOf(System.currentTimeMillis());
        // Generate a random number from 0 to 9999.
        Random random = new Random();
        int randomNum=random.nextInt (10000);
        // Concatenate the strings to create a unique bucket name.
        return prefix + "-" + timestamp + "-" + randomNum;
    }

    public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // Specify the OSS endpoint and bucket name.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = generateUniqueBucketName("demo");
        // Specify the region.
        String region = "cn-hangzhou";
        // Create an OSSClient instance.
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            // 1. Create a bucket.
            ossClient.createBucket(bucketName);
            System.out.println("1. Bucket " + bucketName + " was created.");
            // 2. Upload an object.
            String objectName = "exampledir/exampleobject.txt";
            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            System.out.println("2. Object " + objectName + " was uploaded.");
            // 3. Download the object.
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. Downloaded object content:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. List objects.
            System.out.println("4. Listed objects:");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (Size = " + objectSummary.getSize() + ")");
            }
            // 5. Delete the object.
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. Object " + objectName + " was deleted.");
            // 6. Delete the bucket.
            ossClient.deleteBucket(bucketName);
            System.out.println("6. Bucket " + bucketName + " was deleted.");
        } 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 (ClientException | IOException 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();
            }
        }
    }
}

The following lines provide a sample response:

1. Bucket demo-1731651903982-4074 was created. 
2. Object exampledir/exampleobject.txt was uploaded. 
3. Downloaded object content:
Hello OSS
4. Listed objects:
 - exampledir/exampleobject.txt (Size = 9)
5. Object exampledir/exampleobject.txt was deleted. 
6. Bucket demo-1731651903982-4074 was deleted.