import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.stereotype.Component;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.thorgene.clinical.utils.OssUtil;
public class DownOSSFile {
public static String endpoint;
public static String accessKeyId;
public static String accessKeySecret;
public static String bucketName;
static {
InputStream is = OssUtil.class.getResourceAsStream("/application.properties");
Properties prop = new Properties();
try {
prop.load(is);
} catch (IOException e1) {
e1.printStackTrace();
}
endpoint = prop.getProperty("ali.oss.endpoint");
accessKeyId = prop.getProperty("ali.oss.access-keyid");
accessKeySecret = prop.getProperty("ali.oss.access-secret");
bucketName = prop.getProperty("ali.oss.bucket-name");
}
public static void downFileFromOSS() throws Throwable {
String filePath = "/tmp/aa"; // 保存目录
String objectKey = "objectKey/";
// 创建不同的文件夹目录
File file = new File(filePath);
// 判断文件夹是否存在
if (!file.exists()) {
// 如果文件夹不存在,则创建新的的文件夹
file.mkdirs();
}
// 下载oss静态文件key
String fileName = "thisisafilename.docx";
// 创建OssClient对象
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 获取oss下载的objectName
String objectName = objectKey + fileName;
// 判断文件的保存路径后面是否以/结尾
if (!filePath.endsWith("/")) {
filePath += "/";
}
// 为checkpointFile命名
String checkpointFileName = filePath + fileName.substring(0, fileName.lastIndexOf(".")) + ".ucp";
// 下载请求
DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, objectName);
downloadFileRequest.setDownloadFile(filePath + fileName);// 本地下载文件名称
downloadFileRequest.setPartSize(1 * 1024 * 1024);// 分片大小,取值范围为1B~5GB。
downloadFileRequest.setTaskNum(10);//10个任务并发下载,默认值为1
downloadFileRequest.setEnableCheckpoint(true);// 启动断点续传
downloadFileRequest.setCheckpointFile(checkpointFileName);// 记录本地分片下载结果的文件。
// 下载文件
DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);
// 下载成功时,会返回文件元信息。
downloadRes.getObjectMetadata();
// 关闭OSSClient。
ossClient.shutdown();
}
public static void main(String[] args) {
try {
downFileFromOSS();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}