获取文件详情(下载文件)

更新时间: 2020-03-24

以下代码用于获取文件详情:

// Endpoint以华北三为例,其它Region请按实际情况填写。
String endpoint = "oss.cn-north-3.inspurcloudoss.com";
String accessKey = "<yourAccessKey>";
String secretKey = "<yourSecretKey>";
String bucketName = "<yourBucketName>";
String key = "<yourObjectName>";

//创建OSSClient实例
OSSClientImpl ossClient = new OSSClientImpl(endpoint, accessKey, secretKey);

//查询文件信息
OSSObject object = ossClient.getObject(bucketName, key);
// 读取文件内容
System.out.println("Object content:");
InputStream objectContent = object.getObjectContent();
FileOutputStream downloadFile = new FileOutputStream("downloadFile.txt");
byte[] b = new byte[1024];
int byteCount;
while((byteCount = objectContent.read(b)) != -1){
    downloadFile.write(b, 0 , byteCount);
}
//数据读取完成后,获取的流必须关闭,否则会造成数据泄漏
objectContent.close();
downloadFile.close();