如何用Java代码实现同时将文件上传至阿里云OSS存储服务,并本地桌面保存一份副本?
时间: 2024-11-16 15:28:44 浏览: 14
在Java中,要同时将文件上传到阿里云OSS(Object Storage Service)并本地备份,你需要使用阿里云的SDK以及处理文件I/O操作。这里是一个简单的示例,使用了Aliyun SDK for Java:
首先,确保你已经添加了阿里云OSS SDK依赖。如果你还没有,可以去Maven仓库下载。
```java
import com.aliyuncs.IAcsClient;
import com.aliyuncs.OSSClientBuilder;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import java.io.File;
public class FileUploader {
private static final String ACCESS_KEY_ID = "your_access_key_id";
private static final String ACCESS_KEY_SECRET = "your_access_key_secret";
private static final String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com"; // 替换为你实际的OSS Endpoint
private static final String BUCKET_NAME = "your_bucket_name";
public void uploadAndBackupFile(String localFilePath) {
IAcsClient iAcsClient = new OSSClientBuilder().build(ACCESS_KEY_ID, ACCESS_KEY_SECRET, ENDPOINT);
try {
// 上传到OSS
String objectName = "backup/" + new File(localFilePath).getName(); // 假设备份文件夹名是"backup"
ossUpload(iAcsClient, localFilePath, objectName);
// 本地备份
backupFileToLocal(localFilePath, "local_backup/" + new File(localFilePath).getName());
System.out.println("文件已成功上传到阿里云OSS并本地备份完成.");
} catch (ClientException e) {
e.printStackTrace();
} catch (ServerException e) {
e.printStackTrace();
} finally {
if (iAcsClient != null) {
iAcsClient.shutdown();
}
}
}
private void ossUpload(IAcsClient client, String localFilePath, String objectName) throws ClientException, ServerException {
ossClient.putObject(objectName, new FileInputStream(localFilePath), localFilePath.length());
}
private void backupFileToLocal(String localFilePath, String destinationPath) {
File localBackup = new File(destinationPath);
try {
Files.copy(new File(localFilePath).toPath(), localBackup.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文