codebot:
私は、サイズ・データ・ファイルの3ギガバイトは、GCPクラウドストレージにアップロードする必要があります。私は、アップロードがチュートリアルオブジェクトGCPに例を挙げてみました。私がアップロードしようとしているときしかし、私は、次のエラーを得ました。
java.lang.OutOfMemoryError: Required array size too large
次のように私が試しました、
BlobId blobId = BlobId.of(gcpBucketName, "ft/"+file.getName());
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.get().create(blobInfo, Files.readAllBytes(Paths.get(file.getAbsolutePath())));
return blob.exists();
私はこれをどのように解決できますか?GCPクラウドストレージJavaクライアントを使用して大きなファイルをアップロードするための任意の可能な方法はありますか?
アレクセイAlexeenka:
ストレージのバージョン:
<artifactId>google-cloud-storage</artifactId>
<version>1.63.0</version>
準備:
BlobId blobId = BlobId.of(BUCKET_NAME, date.format(BASIC_ISO_DATE) + "/" + prefix + "/" + file.getName());
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("application/gzip").build();
uploadToStorage(storage, file, blobInfo);
主な方法:
private void uploadToStorage(Storage storage, File uploadFrom, BlobInfo blobInfo) throws IOException {
// For small files:
if (uploadFrom.length() < 1_000_000) {
byte[] bytes = Files.readAllBytes(uploadFrom.toPath());
storage.create(blobInfo, bytes);
return;
}
// For big files:
// When content is not available or large (1MB or more) it is recommended to write it in chunks via the blob's channel writer.
try (WriteChannel writer = storage.writer(blobInfo)) {
byte[] buffer = new byte[10_240];
try (InputStream input = Files.newInputStream(uploadFrom.toPath())) {
int limit;
while ((limit = input.read(buffer)) >= 0) {
writer.write(ByteBuffer.wrap(buffer, 0, limit));
}
}
}
}