google-cloud-storage - 测试对象是否存在于桶中?

标签 google-cloud-storage google-app-engine

我试图弄清楚在 Google Cloud Store 的 Bucket 中测试 Object 是否存在的最有效方法。

这就是我现在正在做的:

try
{
    final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
    if (md == null)
    {
        // do what I need to do here!
    }
}
catch (IOException e)
{
    L.error(e.getMessage());
}

因为根据文档,如果 GcsFilename 不存在,它会返回 null

.

/**
   * @param filename The name of the file that you wish to read the metadata of.
   * @return The metadata associated with the file, or null if the file does not exist.
   * @throws IOException If for any reason the file can't be read.
   */
  GcsFileMetadata getMetadata(GcsFilename filename) throws IOException;

Bucket 上使用 .list() 并检查 .contains() 听起来很昂贵,但其意图很明确。

我个人认为测试 null 来检查是否存在某些东西是不优雅的,而且不像 GCS_SERVICE.objectExists(fileName); 那样直接,但我想我不'开始设计 GCS 客户端 API。我将在我的 API 中创建一个方法来执行此测试。

是否有更有效(及时)或更自记录的方式来进行此测试?

最佳答案

解决方案

这是我最终得到的工作解决方案:

@Nonnull
protected Class<T> getEntityType() { (Class<T>) new TypeToken<T>(getClass()) {}.getRawType(); }

/**
 * purge ObjectMetadata records that don't have matching Objects in the GCS anymore.
 */
public void purgeOrphans()
{
    ofy().transact(new Work<VoidWork>()
    {
        @Override
        public VoidWork run()
        {
            try
            {
                for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable())
                {
                    final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
                    if (md == null)
                    {
                        ofy().delete().entity(bm);
                    }
                }
            }
            catch (IOException e)
            {
                L.error(e.getMessage());
            }
            return null;
        }
    });
}

关于google-cloud-storage - 测试对象是否存在于桶中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25160470/

相关文章:

golang 谷歌存储复制错误

python - Webapp2 strict_slash 返回 KeyError : 'Missing Argument' for url with trailing slash when method has 2 or more args. .. Bug?

php - 使用AppEngine创建云存储桶

javascript - 如何快速刷新 HTML 元素?

shell - 将文件从存储桶拆分并复制到另一个存储桶,无需在本地下载

google-app-engine - 部署应用引擎后的暂存文件桶

node.js - 如何将 BLOB 格式的图像上传到 Firebase 存储?

google-cloud-storage - 向使用 PHP 客户端库上传的文件添加 Access-Control-Allow-Origin header

java - 如果实体的祖先不存在,是否会创建它(Java API)?

java - 加载的实体有父级但没有@Parent