2013-07-09 88 views

回答

2

根據我的解決方案,我只是張貼代碼,以便它可能對某些人找相同的情況下非常有用:

/** 
    * Delete keys/objects from buckets with matching prefix 
    * @param bucket 
    *  Bucket in which delete operation is performed 
    * @param prefix 
    *  String to match the pattern on keys. 
    * @return 
    */ 
    @Override 
    public void deleteFilesInS3(String bucket, String prefix) throws IOException { 
     try{ 
     List<KeyVersion> keys = listAllKeysWithPrefix(bucket, prefix); 
     DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucket); 
     multiObjectDeleteRequest.setKeys(keys); 
     s3EncryptionClient.deleteObjects(multiObjectDeleteRequest); 
     }catch(MultiObjectDeleteException e){ 
      throw new RuntimeException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),e); 
     }catch(AmazonServiceException ase){ 
      throw new AmazonServiceException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),ase); 
     }catch(AmazonClientException ace){ 
      throw new AmazonClientException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),ace); 
     } 
    } 

    /** 
    * Lists all the keys matching the prefix in the given bucket. 
    * @param bucket 
    *  Bucket to search keys 
    * @param prefix 
    *  String to match the pattern on keys. 
    * @return 
    */ 
    @Override 
    public List<KeyVersion> listAllKeysWithPrefix(String bucket,String prefix){ 
     List<KeyVersion> keys = new ArrayList<KeyVersion>(); 
     try{ 
      ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(prefix); 
      ObjectListing objectListing = null; 
      do{ 
       objectListing = s3EncryptionClient.listObjects(listObjectsRequest); 
       for(S3ObjectSummary objectSummary : objectListing.getObjectSummaries()){ 
        keys.add(new KeyVersion(objectSummary.getKey())); 
       } 
       listObjectsRequest.setMarker(objectListing.getNextMarker()); 
      }while(objectListing.isTruncated()); 
     }catch(AmazonServiceException ase){ 
      throw new AmazonServiceException(String.format("Failed to list files with prefix : %s from bucket : %s ",prefix,bucket),ase); 
     }catch(AmazonClientException ace){ 
      throw new AmazonClientException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),ace); 
     }catch(Exception e){ 
      throw new RuntimeException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),e); 
     } 
     return keys; 
    } 
+0

知道自己是否/如何是可以做到的後綴匹配?在匹配中可以使用通配符'*'嗎? – mmcrae

+0

別忘了你可以接受你自己的答案..... –