如何使用Java将目录上传到GCP存储桶

时间:2020-04-10 12:41:40

标签: java google-cloud-platform google-cloud-storage

我当前正在尝试将目录上传到我在GCP上的存储桶中。我设法让它可以上传单个文件。我的UploadObject类如下:

node('devbuild-01') {
  env.JAVA_HOME="${tool 'JDK13'}" //JDK13 is pre-configured in Jenkins
  env.PATH="${env.JAVA_HOME}/bin:${env.PATH}"
  sh 'java -version'
}

在我的主类中利用该另一类的方法如下:

package main;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class UploadObject {

    public static void uploadObject(String bucketName, String objectName, String filePath) throws IOException {

        StorageOptions storageOptions = StorageOptions.newBuilder()
                .setProjectId("<project id>")
                .setCredentials(GoogleCredentials.fromStream(new
                        FileInputStream("<json key>"))).build();
        Storage storage = storageOptions.getService();
        BlobId blobId = BlobId.of(bucketName, objectName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
        storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));

        System.out.println("File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
    }

}

此方法从gzip文件中提取内容,然后尝试将内容上传到GCP。但是,我收到此错误结果:

private void btnLoadEngineActionPerformed(ActionEvent arg0) throws IOException {
    if (chooser.files.isEmpty()) {
        throw new FileNotFoundException("No files were selected!");
    } else {
        UploadObject upload = new UploadObject();
        Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
        for (File f : chooser.files) {
            String fileName = f.getParent() + "\\" + f.getName().substring(0, f.getName().indexOf(".tar.gz"));
            File dest = new File(fileName);
            archiver.extract(f, dest);
            upload.uploadObject(bucketId, dest.getName(), dest.getPath() + "\\");
        }
    }
}

我似乎在网上找不到其他地方可以解释如何执行此操作,因此我想问自己,看看是否有人有任何想法。就像我说的那样,它可以正常上传常规文件,但是当我尝试目录时,它将引发此异常。

0 个答案:

没有答案