背景
又拍云图库需要迁移到其他图库,需要将里面的图片下载到本地。本次依赖又拍云提供的SDK,将SDK下载到本地,导入IDEA中。
SDK地址
https://github.com/upyun/java-sdk/archive/master.zip
代码实现
public static void main(String[] args) throws IOException, UpException {
// 初始化空间
restManager = new RestManager(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
// ****** 可选设置 begin ******
// 切换 API 接口的域名接入点,默认为自动识别接入点
restManager.setApiDomain(RestManager.ED_AUTO);
// 设置连接超时时间,默认为30秒
restManager.setTimeout(60);
// 参数可以换成其他目录路径
String dirPath ="/";
Map<String, String> params = new HashMap<String, String>();
params.put(UpYun.PARAMS.KEY_X_LIST_LIMIT.getValue(), "10000");
Response response = restManager.readDirIter(dirPath, params);
String str = response.body().string();
List<String> list = Arrays.stream(str.split("\n")).map(s -> s.split("\t")[0]).collect(Collectors.toList());
System.out.println(list);
for (String s : list) {
Response res = restManager.readFile(dirPath+File.separator + s);
// 写入文件地址,替换为实际本地地址
String fileName = "C:\\Users\\xxx\\Downloads\\blogPic"+dirPath+File.separator + s; // 替换为你想要的文件名
// 获取图片的二进制流
InputStream inputStream = null;
try {
inputStream = res.body().byteStream();
// 写入文件
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.flush();
System.out.println("Image has been written to " + fileName);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}