OBS JAVA SDK 实践8:批量下载文件(e.g 下载文件夹)
1 背景介绍 & 效果展示
通过OBS JAVA SDK可以实现批量下载文件,如下载文件夹,效果如下。
注:有关标准存储、低频访问、归档存储三种存储类型的更多信息,参考链接:https://support.huaweicloud.com/usermanual-obs/zh-cn_topic_0050321036.html
图1 桶下面有“FunctionGraphDemo-VideoConvert/”为前缀的文件夹
图2 把上图中的文件夹下载到本地"C:/software/"目录下
2 java代码参考
前提:
需要先下载OBS最新的JAVA SDK,参考官网链接:https://developer.huaweicloud.com/sdk?OBS,并在自己的项目中导入SDK中的JAR包。
public static void main(String[] args) throws IOException {
// 需要将endPoint/ak/sk更新为实际信息
String endPoint = "https://your-endpoint";
String ak = "*** Provide your Access Key ***";
String sk = "*** Provide your Secret Key ***";
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
try
{
String bucketName = "bucketXXX"; // 需要将bucketName更新为实际信息
String fileLocatePrefix = "C:/software/"; // 需要下载到本地哪个目录,这里面举例"C:/software/"
ListObjectsRequest request = new ListObjectsRequest(bucketName);
// 指定下载"FunctionGraphDemo-VideoConvert/"文件夹
request.setPrefix("FunctionGraphDemo-VideoConvert/");
request.setMaxKeys(500);
ObjectListing result;
System.out.println("Objects:");
do{
result = obsClient.listObjects(request);
for (ObsObject obsObject : result.getObjects())
{
System.out.println("\t" + obsObject.getObjectKey());
DownloadFileRequest requestDownload = new DownloadFileRequest(bucketName, obsObject.getObjectKey());
requestDownload.setDownloadFile(fileLocatePrefix+obsObject.getObjectKey());
// 设置分段下载时的最大并发数
requestDownload.setTaskNum(5);
// 设置分段大小为10MB
requestDownload.setPartSize(10 * 1024 * 1024);
// 开启断点续传模式
requestDownload.setEnableCheckpoint(true);
try{
// 进行断点续传下载
DownloadFileResult resultDownload = obsClient.downloadFile(requestDownload);
}catch (ObsException e) {
System.out.println("Response Code: " + e.getResponseCode());
System.out.println("Error Message: " + e.getErrorMessage());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getErrorRequestId());
System.out.println("Host ID: " + e.getErrorHostId());
}
}
System.out.println("------------------------------");
request.setMarker(result.getNextMarker());
}while(result.isTruncated());
}
}
3 附录链接
OBS JAVA SDK使用方法,官网参考链接:https://support.huaweicloud.com/sdk-java-devg-obs/zh-cn_topic_0142815558.html
- 点赞
- 收藏
- 关注作者
评论(0)