如何在java中逐行上传文件到谷歌云存储

时间:2018-03-27 10:10:58

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

我有以下代码:

 String fullFileUrl = fileUrl;
 Storage storage = StorageServiceHolder.getStorage();
 BlobId blobId = GCSHelper.uri2blobId(fullFileUrl);

 while (!queue.isEmpty()) {
     try {
         String line = queue.poll(1000, TimeUnit.SECONDS);
         InputStream inputStream = new ByteArrayInputStream(line.getBytes());

         BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
         Blob blob = storage.create(blobInfo, inputStream);

      } catch (InterruptedException e) {
          log.error("Get interrupt while writing to Goolge Cloud Storage" + e.getMessage(), e);
 }

因为我逐行上传数据,每次都删除以前的数据,结束while循环,GCS中的文件只包含最后一行。

如何逐行上传并将其附加到现有数据?

1 个答案:

答案 0 :(得分:2)

我设法使用管道而不是队列来解决它:

    private PipedInputStream inStream;
    inStream = .....


    String fullFileUrl = fileUrl;
    Storage storage = StorageServiceHolder.getStorage();
    BlobId blobId = GCSHelper.uri2blobId(fullFileUrl);

    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
    Blob blob = storage.create(blobInfo, inStream);

    }