全部產品
Search
文件中心

Object Storage Service:Java下載檔案

更新時間:Oct 25, 2024

預設情況下,在受版本控制的儲存空間(Bucket)中調用GetObject介面僅返迴文件(Object)的目前的版本。

注意事項

背景資訊

對某個Bucket執行GetObject操作時,分以下三種情況:

  • 如果該Bucket中Object的目前的版本是刪除標記(Delete Marker),則返回404 Not Found。

  • 如果在查詢參數中指定Object的versionId,則返回指定的Object版本。當versionId指定為“null”時,則返回versionId為“null”的Object版本。

  • 通過指定versionId的方式來擷取刪除標記時,則返回405 Method Not Allowed。

範例程式碼

以下代碼用於下載檔案。

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Demo {
    public static void main(String[] args) {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑,例如exampledir/exampleobject.txt。Object完整路徑中不能包含Bucket名稱。
        String objectName = "exampledir/exampleobject.txt";
        // 填寫Object的VersionId,例如CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****。
        String versionid = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // 封裝GetObject請求。
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);            
            getObjectRequest.setVersionId(versionid);
            // ossObject包含檔案所在的儲存空間名稱、檔案名稱、檔案中繼資料以及一個輸入資料流。
            OSSObject ossObject = ossClient.getObject(getObjectRequest);

            // 查看已下載Object的VersionId。
            System.out.println("Get Object versionid:" +  ossObject.getObjectMetadata().getVersionId());
            // 讀取指定VersionId的Object內容。
            System.out.println("Object content:");
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            while (true) {
                String line = reader.readLine();
                if (line == null) break;
                System.out.println("\n" + line);
            }

        } 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 {
            // 關閉OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}            

關於下載檔案的API介面說明,請參見GetObject