是时候使用 java(BlobstoreService) 更改 Google 云存储中下载的文件名了。 BlobstoreService 中是否有任何规定可以在下载该文件之前更改文件名?有没有什么有用的 API 可以更改文件名?这里发生的事情是,当我在 GCS 中保存文件时,它将生成一个 blob key。 Google云存储中的文件类型也发生了变化。现在我只想在下载之前更改文件名以及文件类型。
最佳答案
您可以通过读入文件并使用新名称保存来重命名文件。以下是一些入门示例代码,您可能需要添加自己的删除功能才能删除旧文件:
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();
}
关于java - 是否可以使用java更改谷歌云存储文件的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405700/