如何使用 JAVA 访问 Google Cloud Storage 中带有前缀的子文件夹?

问题描述 投票:0回答:0

我正在使用云存储来保存一些文件(Blob)我想要存档的是访问以下路径中的这些文件:

***xml/032023/Files/Entreprise/deductions***

我阅读文档的理解是这必须是一个前缀,为此我使用以下代码

    public static String directory= "xml/032023/Files/Entreprise/deductions"
        

public static List<File> getFilesxml() throws IOException{

         List<File> listFiles = new ArrayList<>();
         List<String> names = new ArrayList<>();

     try{
        LOGGER.info("Setting Storage Options ");
         Storage storage = StorageOptions.newBuilder().setProjectId(project_id).build().getService();
         Page<Blob>  blobs = storage.list(bucketName, Storage.BlobListOption.prefix(directory),
Storage.BlobListOption.currentDirectory()));

//Also I've tried not using Storage.BlobListOption.currentDirectory()

         
        for(Blob blob: blobs.iterateAll()){
            LOGGER.info("blobname: "+blob.getName());

            LOGGER.info("name:"+blob.getName());
            names.add(blob.getName());

            listFiles = downfilesFromFolder(names);
        }

     }catch (Exception e){

     }
    return listFiles;
    }

如果您想知道获取一些文件并根据需要使用它们后,接下来是下载方法

public static List<File> downfilesFromFolder(List<String> names) throws IOException {
    File file = null;
    List<File> files = new ArrayList<>();
    try {
        for(String name: names){

            Storage storage = StorageOptions.getDefaultInstance().getService();

            Blob blob = storage.get(BlobId.of(bucketName,  name));
            String newName= name.replace("xml/","");
           //This replace is beacause when I log the blobname  in the first path was xml/deduction_february.xml and after this the blobname is now deduction_february.xml
            blob.downloadTo(Paths.get("/tmp/" + newName));

            ReadChannel readChannel = blob.reader();
            file = new File("/tmp/" + newName);

            FileOutputStream fileOuputStream = new FileOutputStream(file);
            fileOuputStream.getChannel().transferFrom(readChannel, 0, Long.MAX_VALUE);
            fileOuputStream.close();
            files.add(file);
        }

    } catch (Exception e){
        LOGGER.info("Error: " + e.getMessage());
    }
    return files;
}

当我记录 blobname 时,云控制台中没有显示任何内容,也没有执行后续步骤,我如何访问新路径(前缀)中的那些 blob?当我的文件位于第一个路径“xml”但现在位于其他路径时,这非常有效,我和其他人将非常感谢对此的帮助,感谢您的帮助。

java google-cloud-platform google-cloud-storage prefix blobstore
© www.soinside.com 2019 - 2024. All rights reserved.