【问题标题】:Is it possible to change the filename of a google cloud storage file using java?是否可以使用 java 更改谷歌云存储文件的文件名?
【发布时间】:2014-06-17 19:31:18
【问题描述】:

是时候使用 java(BlobstoreService) 在 Google Cloud Storage 中更改下载的文件名了。 BlobstoreService 中是否有任何规定可以在下载该文件之前更改文件名?是否有任何有用的 API 来更改文件名?这里发生的事情是,当我在 GCS 中保存文件时,它会生成一个 blob 密钥。并且文件类型在谷歌云存储中也发生了变化。现在我只想在下载之前更改文件名,以及文件的类型。

【问题讨论】:

  • 您找到在 GCS 中重命名文件的方法了吗?如果是这样,你能和我们分享一下吗?

标签: java google-app-engine google-cloud-storage blobstore


【解决方案1】:

您可以通过读取文件并使用新名称保存来重命名文件。这里有一些示例代码可以帮助您入门,您可能需要添加自己的删除函数才能删除旧文件:

public void moveFile(String fileName, String bucket, String newFilename, String contentType) throws IOException {
    byte[] bytes = loadFile(bucket, fileName);
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    saveToGcs(bucket, fileName, in, contentType);
}

public byte[] loadFile(String bucket, String fileName) throws IOException {
    GcsFilename gcsFileName = new GcsFilename(bucket, fileName);
    GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0);
    InputStream in = Channels.newInputStream(readChannel);
    return IOUtils.toByteArray(in);
}

private void saveToGcs(String bucket, String filename, InputStream inputStream, String mimeType) throws IOException {
    GcsFilename gcsFilename = new GcsFilename(bucket, filename);
    GcsFileOptions options = new GcsFileOptions.Builder().mimeType(mimeType).acl("public-read").build();
    GcsOutputChannel writeChannel = gcsService.createOrReplace(gcsFilename, options);
    BufferedOutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(writeChannel));
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();
    writeChannel.close();
}

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 2014-09-30
    • 2023-03-30
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多