Search code examples
javaamazon-s3file-upload

How to upload folder with subfolder to amazon s3?


I need upload folder with subfolders on amazon s3. I try upload with this snipet.

    for (Path path : directoryWalk("/home/rmuhamedgaliev/tmp/eota7tas0cdlg2ufq5mlke7olf/")){
       if (!path.getParent().toString().equals("eota7tas0cdlg2ufq5mlke7olf")){
        amazonS3Client.putObject("*****", "/plans/eota7tas0cdlg2ufq5mlke7olf/" + path.getParent().toString() + "/" + path.getFileName(), new File(path.toString()));
       } else {
        amazonS3Client.putObject("*******", "/plans/eota7tas0cdlg2ufq5mlke7olf/" + path.getFileName(), new File(path.toString()));
       }
    }

But this code create full path files with ("/home/rmuhamedgaliev/tmp/eota7tas0cdlg2ufq5mlke7olf"). How to upload it with path ("/plans/eota7tas0cdlg2ufq5mlke7olf/{subfolders and files}")

    private List<Path> directoryWalk(String path) throws IOException {
        final List<Path> files = new ArrayList<>();
        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                files.add(file);
                return FileVisitResult.CONTINUE;
            }
        });
        return files;
    }

Solution

  • Have you looked at the TransferManager in the AWS SDK for Java? You could use the uploadDirectory method for this. The javadoc is here. In essence, you could do something like this:

    transferManager.uploadDirectory(bucketName, "plans/eota7tas0cdlg2ufq5mlke7olf/", new File("/home/rmuhamedgaliev/tmp/eota7tas0cdlg2ufq5mlke7olf/"), true);