https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-java
1.jar包
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
<version>1.51.0</version>
</dependency>
2.添加凭证
a.在GCP控制台中,API和服务-凭证 页面。
b.转到创建服务帐户主页
从“服务帐户”下拉列表中,选择“新建服务帐户”。
在“服务帐户名称”字段中,输入名称。
从“角色”下拉列表中,选择“项目”>“所有者”。
注意:“角色”字段授权您的服务帐户访问资源。您可以稍后使用GCP控制台查看和更改此字段。如果您正在开发生产应用程序,请指定比项目>所有者更细化的权限。有关更多信息,请参阅向服务帐户授予角色。
c.单击“创建”包含密钥下载到计算机的JSON文件。
3.把凭证配置到环境中
GOOGLE_APPLICATION_CREDENTIALS E:\softpackage\windows\My First Project-3b9f1c96ee61.json
linux
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"
window
set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
4.上传
package com.example.demo;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class GoogleStroageUpload {
public static void main(String[] args) throws UnsupportedEncodingException {
// Instantiates a client
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get("yinzhen-ltd");
if(bucket == null) {
System.out.println("bucket 不存在");
}else {
System.out.println("bucket 存在");
}
InputStream content = new ByteArrayInputStream("ceshi111, World!".getBytes("UTF-8"));
Blob blob = bucket.create("1001/546/hell111", content, "text/plain");
System.out.println(blob);
}
}
5.下载
package com.example.demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import com.google.cloud.ReadChannel;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class GoogleStorageDownload {
public static void main(String[] args) throws Exception {
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get("yinzhen-ltd");
Blob blob = bucket.get("testMyBolb");
if (blob == null) {
System.out.println("No such object");
return;
}
PrintStream writeTo = System.out;
writeTo = new PrintStream(new FileOutputStream(new File("E:/test.log")));
if (blob.getSize() < 1_000_000) {
// Blob is small read all its content in one request
byte[] content = blob.getContent();
writeTo.write(content);
} else {
// When Blob size is big or unknown use the blob's channel reader.
try (ReadChannel reader = blob.reader()) {
WritableByteChannel channel = Channels.newChannel(writeTo);
ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
while (reader.read(bytes) > 0) {
bytes.flip();
channel.write(bytes);
bytes.clear();
}
}
}
writeTo.close();
}
}