写一段下载OSS文件的代码
时间: 2024-06-12 13:08:20 浏览: 124
以下是使用Java SDK下载OSS文件的示例代码:
```java
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import java.io.*;
public class OSSDownloadFileDemo {
public static void main(String[] args) {
String endpoint = "<yourEndpoint>";
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";
String localFilePath = "<yourLocalFilePath>";
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, objectName));
InputStream inputStream = ossObject.getObjectContent();
OutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully.");
} catch (IOException e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
}
}
}
```
其中需要填写的参数包括:
- endpoint:OSS服务的API域名。
- accessKeyId和accessKeySecret:OSS账户的AccessKey ID和AccessKey Secret。
- bucketName:OSS存储空间的名称。
- objectName:要下载的文件在OSS中的路径。
- localFilePath:本地文件保存的路径。
该示例代码通过`ossClient.getObject()`方法获取OSS对象,然后通过输入流读取该对象的内容,并将内容写入到本地文件中。最后关闭输入流和输出流,并关闭OSS客户端。
阅读全文