Amazon Web Services (AWS) S3 Java create a sub directory (object)

前端 未结 6 1217
孤城傲影
孤城傲影 2021-01-31 17:24

I am familiar with AWS Java SDK, I also tried to browse the corresponding Javadoc, but I could not realize how do I create a sub directory, i.e., a directory object within a buc

6条回答
  •  爱一瞬间的悲伤
    2021-01-31 18:13

    S3 doesn't see directories in the traditional way we do this on our operating systems. Here is how you can create a directory:

    public static void createFolder(String bucketName, String folderName, AmazonS3 client) {
        // create meta-data for your folder and set content-length to 0
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(0);
    
        // create empty content
        InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
    
        // create a PutObjectRequest passing the folder name suffixed by /
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
                    folderName + SUFFIX, emptyContent, metadata);
    
        // send request to S3 to create folder
        client.putObject(putObjectRequest);
    }
    

    As casablanca already said you can upload files to directories like this:

    s3.putObject("someBucket", "foo/bar1", file1);
    

    Read the whole tutorial here for details, and the most important thing is you will find info how to delete the directories.

提交回复
热议问题