Quellcode durchsuchen

oss-sdk 中 OssStoreClient 添加一个 getObject 方法, 获取对象文件

reghao vor 1 Jahr
Ursprung
Commit
937a94cf09
1 geänderte Dateien mit 47 neuen und 0 gelöschten Zeilen
  1. 47 0
      oss-sdk/src/main/java/cn/reghao/oss/sdk/OssStoreClient.java

+ 47 - 0
oss-sdk/src/main/java/cn/reghao/oss/sdk/OssStoreClient.java

@@ -170,6 +170,53 @@ public class OssStoreClient {
         return false;
     }
 
+    public void getObject(String objectName, String filePath) {
+        try {
+            String version = "1.0.0";
+            String api = String.format("%s/%s?client=%s", endpoint, objectName, version);
+            HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
+                    .version(HttpClient.Version.HTTP_1_1)
+                    .GET()
+                    .build();
+
+            HttpResponse<InputStream> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofInputStream());
+            int statusCode = httpResponse.statusCode();
+            if (statusCode == 200) {
+                String localPath = saveFile(filePath, httpResponse.body());
+                log.info("saved to {}", localPath);
+            } else {
+                log.error("{}", statusCode);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public String saveFile(String filePath, InputStream in) {
+        File file = new File(filePath);
+        File parentDir = file.getParentFile();
+        try {
+            if (!parentDir.exists()) {
+                FileUtils.forceMkdir(parentDir);
+            }
+
+            FileOutputStream fos = new FileOutputStream(file);
+            // 1MiB
+            int len = 1024*1024*5;
+            byte[] buf = new byte[len];
+            int readLen;
+            while ((readLen = in.read(buf, 0, len)) != -1) {
+                fos.write(buf, 0, readLen);
+            }
+            fos.close();
+            return filePath;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
     public void getObject(String objectName) {
         try {
             String version = "1.0.0";