import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TencentCloudFileOperation {
public static void uploadFileToTencentCloud(String filePath, String bucketName, String secretId, String secretKey) {
BasicCOSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
COSClient cosClient = new COSClient(credentials, clientConfig);
try {
File file = new File(filePath);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, file.getName(), file);
cosClient.putObject(putObjectRequest);
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}
public static void downloadFileFromTencentCloud(String bucketName, String fileName, String savePath, String secretId, String secretKey) {
BasicCOSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
COSClient cosClient = new COSClient(credentials, clientConfig);
try {
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, fileName);
FileOutputStream fos = new FileOutputStream(new File(savePath));
cosClient.getObject(getObjectRequest, fos);
fos.close();
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}
public static void main(String[] args) {
String bucketName = "your_bucket_name";
String secretId = "your_secret_id";
String secretKey = "your_secret_key";
String uploadFilePath = "123.xlsx";
uploadFileToTencentCloud(uploadFilePath, bucketName, secretId, secretKey);
String downloadSavePath = "downloaded_123.xlsx";
downloadFileFromTencentCloud(bucketName, "123.xlsx", downloadSavePath, secretId, secretKey);
}
}
在上述代码中:
-
uploadFileToTencentCloud
方法用于上传文件。- 您需要将
your_bucket_name
替换为您在腾讯云创建的存储桶名称。 - 将
your_secret_id
和your_secret_key
替换为您获取的腾讯云访问密钥。
- 您需要将
-
downloadFileFromTencentCloud
方法用于下载文件。savePath
是指定下载后文件保存的本地路径。
在 main
方法中,首先调用上传方法将文件上传,然后调用下载方法将文件下载到指定的本地路径。
请注意,在实际使用时,您需要根据自己的腾讯云配置和需求进行相应的调整。如果遇到问题,可以查看错误输出信息以便进一步排查。