You need to enable JavaScript to run this app.
导航
普通下载(Java SDK)
最近更新时间:2024.02.04 18:30:53首次发布时间:2021.11.27 17:58:44

普通下载是指通过 getObject 接口下载单个对象(Object)。TOS Java SDK 支持将对象下载到内存、下载到本地文件两种方式,且支持下载对象时重写 HTTP 响应头。

注意事项

  • 下载对象前,您必须具有 tos:GetObject 权限,具体操作,请参见权限配置指南
  • 对于开启多版本的桶,下载指定版本对象时,您必须具有 tos:GetObjectVersion 权限,具体操作,请参见权限配置指南
  • 如果应用程序会在同一时刻大量下载同一个对象,您的访问速度会受到 TOS 带宽及地域的限制。建议您使用 CDN 产品,提升性能的同时也能降低您的成本。通过 CDN 访问 TOS 的详细信息,请参见使用 CDN 加速访问 TOS 资源

下载到内存

Java SDK 的 getObject 接口返回一个 InputStream 对象,可在内存中直接读取。
以下代码展示如何下载目标桶 bucket-example 中的 example_dir 目录下的 example_object.txt 文件,并在内存中直接读取打印字符串。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.model.object.GetObjectV2Input;
import com.volcengine.tos.model.object.GetObjectV2Output;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GetObjectInStringExample {
    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        // 对象名
        String objectKey = "example_dir/example_object.txt";

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        GetObjectV2Input input = new GetObjectV2Input().setBucket(bucketName).setKey(objectKey);
        // 以下代码展示如何将数据下载到内存中并逐行读取打印
        try(GetObjectV2Output output = tos.getObject(input);
            BufferedReader reader = new BufferedReader(new InputStreamReader(output.getContent()))) {
            System.out.println("begin to read content in object.");
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
        } catch (IOException e) {
            System.out.println("read data in object failed");
            e.printStackTrace();
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("getObject failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (TosServerException e) {
            // 操作失败,捕获服务端异常,可以获取到从服务端返回的详细错误信息
            System.out.println("getObject failed");
            System.out.println("StatusCode: " + e.getStatusCode());
            System.out.println("Code: " + e.getCode());
            System.out.println("Message: " + e.getMessage());
            System.out.println("RequestID: " + e.getRequestID());
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("getObject failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

下载到本地文件

Java SDK 的 getObject 接口返回一个 InputStream 对象,可将其读取写入本地文件。您也可以通过 getObjectToFile 接口直接下载到本地文件。

通过 getObject 接口下载到本地文件

以下代码展示如何下载目标桶 bucket-example 中的 example_dir 目录下的 example_object.txt 文件到本地。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.model.object.GetObjectV2Input;
import com.volcengine.tos.model.object.GetObjectV2Output;

import java.io.*;
import java.util.Map;

public class GetObjectToFileWithInputStreamExample {
    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        // 对象名
        String objectKey = "example_dir/example_object.txt";
        // 对象数据保存的本地文件路径,需保证不存在,否则会覆盖原有文件
        String filePath = "example_dir/example_file.txt";

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        GetObjectV2Input input = new GetObjectV2Input().setBucket(bucketName).setKey(objectKey);
        // 以下代码展示如何将数据下载到本地文件
        File file = new File(filePath);
        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            // 此处判断文件路径的父文件夹是否存在,不存在则创建父文件夹
            // 如果父文件夹不存在且不创建,直接写入会报 FileNotFoundException
            file.getParentFile().mkdirs();
        }
        try(GetObjectV2Output output = tos.getObject(input);
            FileOutputStream fos = new FileOutputStream(file)) {
            System.out.println("begin to read content in object to file.");
            if (output.getContent() != null) {
                byte[] buffer = new byte[4096];
                int length;
                while ((length = output.getContent().read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                }
            }
            fos.flush();
            System.out.println("getObject succeed.");
            System.out.println("object's etag is " + output.getEtag());
            System.out.println("object's lastModified is " + output.getLastModified());
            System.out.println("object's crc64 value is " + output.getHashCrc64ecma());
            System.out.println("object's storageClass is " + output.getStorageClass());
            System.out.println("object's cacheControl is " + output.getCacheControl());
            System.out.println("object's contentDisposition is " + output.getContentDisposition());
            System.out.println("object's contentEncoding is " + output.getContentEncoding());
            System.out.println("object's contentLanguage is " + output.getContentLanguage());
            System.out.println("object's contentType is " + output.getContentType());
            if (output.getCustomMetadata() != null) {
                System.out.println("object has custom meta data.");
                for (Map.Entry<String, String> entry : output.getCustomMetadata().entrySet()) {
                    System.out.println("custom meta key: " + entry.getKey() + ", value: " + entry.getValue());
                }
            }
        } catch (IOException e) {
            System.out.println("read data in object failed");
            e.printStackTrace();
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("getObject failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (TosServerException e) {
            // 操作失败,捕获服务端异常,可以获取到从服务端返回的详细错误信息
            System.out.println("getObject failed");
            System.out.println("StatusCode: " + e.getStatusCode());
            System.out.println("Code: " + e.getCode());
            System.out.println("Message: " + e.getMessage());
            System.out.println("RequestID: " + e.getRequestID());
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("getObject failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

通过 getObjectToFile 接口下载到本地文件

以下代码展示如何下载目标桶 bucket-example 中的 example_dir 目录下的 example_object.txt 文件到本地。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.model.object.GetObjectToFileInput;
import com.volcengine.tos.model.object.GetObjectToFileOutput;
import com.volcengine.tos.model.object.GetObjectV2Input;

import java.util.Map;

public class GetObjectToFileExample {
    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        // 对象名
        String objectKey = "example_dir/example_object.txt";
        // 对象数据保存的本地文件路径,需保证不存在,否则会覆盖原有文件
        String filePath = "example_dir/example_file.txt";

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try{
            GetObjectV2Input input = new GetObjectV2Input().setBucket(bucketName).setKey(objectKey);
            // 以下代码展示如何将数据下载到本地文件
            GetObjectToFileInput fileInput = new GetObjectToFileInput().setFilePath(filePath).setBucket(bucketName).setKey(objectKey);
            GetObjectToFileOutput fileOutput = tos.getObjectToFile(fileInput);
            System.out.println("getObjectToFile succeed.");
            System.out.println("object's etag is " + fileOutput.getEtag());
            System.out.println("object's lastModified is " + fileOutput.getLastModified());
            System.out.println("object's crc64 value is " + fileOutput.getHashCrc64ecma());
            System.out.println("object's storageClass is " + fileOutput.getStorageClass());
            System.out.println("object's cacheControl is " + fileOutput.getCacheControl());
            System.out.println("object's contentDisposition is " + fileOutput.getContentDisposition());
            System.out.println("object's contentEncoding is " + fileOutput.getContentEncoding());
            System.out.println("object's contentLanguage is " + fileOutput.getContentLanguage());
            System.out.println("object's contentType is " + fileOutput.getContentType());
            if (fileOutput.getCustomMetadata() != null) {
                System.out.println("object has custom meta data.");
                for (Map.Entry<String, String> entry : fileOutput.getCustomMetadata().entrySet()) {
                    System.out.println("custom meta key: " + entry.getKey() + ", value: " + entry.getValue());
                }
            }
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("getObject failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (TosServerException e) {
            // 操作失败,捕获服务端异常,可以获取到从服务端返回的详细错误信息
            System.out.println("getObject failed");
            System.out.println("StatusCode: " + e.getStatusCode());
            System.out.println("Code: " + e.getCode());
            System.out.println("Message: " + e.getMessage());
            System.out.println("RequestID: " + e.getRequestID());
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("getObject failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

下载时重写 HTTP 响应头

Java SDK 支持在下载对象时指定服务端返回特定的 HTTP 响应 Header 信息。
以下代码展示如何下载目标桶 bucket-example 中的 example_dir 目录下的 example_object.txt 文件到本地,并重写 HTTP 响应头。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.model.object.GetObjectV2Input;
import com.volcengine.tos.model.object.GetObjectV2Output;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GetObjectWithResponseHeaderExample {
    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        // 对象名
        String objectKey = "example_dir/example_object.txt";

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        GetObjectV2Input input = new GetObjectV2Input().setBucket(bucketName).setKey(objectKey)
                .setResponseContentType("application/json");
        // 以下代码展示如何将数据下载到内存中并逐行读取打印
        try(GetObjectV2Output output = tos.getObject(input);
            BufferedReader reader = new BufferedReader(new InputStreamReader(output.getContent()))) {
            System.out.println("begin to read content in object.");
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            System.out.println("getObject succeed, object's content-type is " + output.getContentType());
        } catch (IOException e) {
            System.out.println("read data in object failed");
            e.printStackTrace();
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("getObject failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (TosServerException e) {
            // 操作失败,捕获服务端异常,可以获取到从服务端返回的详细错误信息
            System.out.println("getObject failed");
            System.out.println("StatusCode: " + e.getStatusCode());
            System.out.println("Code: " + e.getCode());
            System.out.println("Message: " + e.getMessage());
            System.out.println("RequestID: " + e.getRequestID());
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("getObject failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

相关文档

关于下载对象的 API 文档,请参见 GetObject