java 使用腾讯云COS存储桶 配置密钥 上传下载等 示例代码
时间: 2024-05-06 08:19:11 浏览: 14
以下是使用腾讯云COS存储桶进行文件上传和下载的示例代码,其中包括了配置密钥的部分。
```
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import com.qcloud.cos.transfer.Download;
import java.io.File;
public class COSDemo {
private static final String SECRET_ID = "yourSecretId";
private static final String SECRET_KEY = "yourSecretKey";
private static final String REGION_NAME = "yourRegionName";
private static final String BUCKET_NAME = "yourBucketName";
public static void main(String[] args) {
// 初始化 COS 客户端
BasicCOSCredentials credentials = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
ClientConfig clientConfig = new ClientConfig(new Region(REGION_NAME));
COSClient cosClient = new COSClient(credentials, clientConfig);
// 初始化 TransferManager
TransferManager transferManager = new TransferManager(cosClient);
// 上传文件
String key = "test.txt";
File localFile = new File("/path/to/local/file");
ObjectMetadata objectMetadata = new ObjectMetadata();
Upload upload = transferManager.upload(BUCKET_NAME, key, localFile, objectMetadata);
try {
upload.waitForCompletion();
System.out.println("File uploaded successfully.");
} catch (InterruptedException e) {
System.err.println("Failed to upload file: " + e.getMessage());
}
// 下载文件
Download download = transferManager.download(BUCKET_NAME, key, new File("/path/to/local/file"));
try {
download.waitForCompletion();
System.out.println("File downloaded successfully.");
} catch (InterruptedException e) {
System.err.println("Failed to download file: " + e.getMessage());
}
// 关闭 COS 客户端和 TransferManager
transferManager.shutdownNow();
cosClient.shutdown();
}
}
```
在上面的代码中,你需要将 `yourSecretId` 和 `yourSecretKey` 替换为腾讯云账号的 SecretId 和 SecretKey,将 `yourRegionName` 替换为存储桶所在地域的名称,将 `yourBucketName` 替换为存储桶的名称。
另外,你需要将 `/path/to/local/file` 替换为本地文件的路径。