gpt4 book ai didi

java - 使用 Java SDK 从 Google Cloud Storage 下载对象字节范围

转载 作者:行者123 更新时间:2023-11-30 12:05:04 28 4
gpt4 key购买 nike

我正在尝试从 Google Cloud Storage 下载一个字节范围, 使用他们的 Java SDK .

我可以像这样下载整个文件。

Storage mStorage; // initialized and working

Blob blob = mStorage.get(pBucketName, pSource);

try (ReadChannel reader = mStorage.reader(blob.getBlobId())) {
// read bytes from read channel
}

如果我愿意,我可以ReadChannel#seek(long) 直到达到所需的起始字节,然后从该点下载一个范围,但这似乎效率低下(虽然我不完全知道实现中发生了什么。)

理想情况下,我想将 Range: bytes=start-end header 指定为 shown in the Google Cloud Storage REST API ,但我不知道如何在 Java 中设置 header 。

如何在 Java SDK Storage get 调用中指定字节范围,或指定 header ,以便高效地下载所需的字节范围?

最佳答案

我知道您正在尝试使用 Google Cloud 的特定接口(interface),但您可能还不知道另一种方式:Google Cloud 可以插入 Java 的 NIO 接口(interface)。您可以获得存储桶上文件的 Path 并正常使用它:获取 SeekableChannel进入你的文件,然后调用 position(long)获取您想要阅读的位置的方法。

这是我测试过的示例代码:

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

(...)

public static void readFromMiddle(String path, long offset, ByteBuffer buf) throws IOException {
// Convert from a string to a path, using available NIO providers
// so paths like gs://bucket/file are recognized (provided you included the google-cloud-nio
// dependency).
Path p = Paths.get(URI.create(path));
SeekableByteChannel chan = Files.newByteChannel(p, StandardOpenOption.READ);
chan.position(offset);
chan.read(buf);
}


您会发现这是普通的 Java 代码,除了我们创建 Path 的不寻常方式外,没有什么特别之处。这就是 NIO 的美妙之处。要使此代码能够理解“gs://”URL,您需要添加 google-cloud-nio 依赖项。对于 Maven,它是这样的:

    <dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-nio</artifactId>
<version>0.107.0-alpha</version>
</dependency>

仅此而已。

The documentation page展示了如何为其他依赖项管理器执行此操作并提供了一些附加信息。

关于java - 使用 Java SDK 从 Google Cloud Storage 下载对象字节范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56636943/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com