How to read S3 file from AWS Lambda Function written in Java?

I have written a AWS Lambda Function, Its objective is that on invocation - it read the contents of a file say x.db, get a specific value out of it and return to the caller.But this x.db file changes time to time. So I would like to upload this x.db file to S3 and read it from AWS Lambda function as like reading a file.

        File xFile = new File("S3 file in x.db");

How to read such x.db S3 file from AWS Lambda Function written in Java ?

Answers 1

  • Use the Java S3 SDK. If you upload a file called x.db to an S3 bucket mybucket, it would look something like this:

    import com.amazonaws.services.s3.*;
    import com.amazonaws.services.s3.model.*;
    
    ...
    AmazonS3 client = new AmazonS3Client();
    S3Object xFile = client.getObject("mybucket", "x.db");
    InputStream contents = xFile.getObjectContent();
    

    In addition, you should ensure the role you've assigned to your lambda function has access to the S3 bucket. Apply a policy like this:

    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Action": [
        "s3:*"
      ],
      "Resource": [
        "arn:aws:s3:::mybucket",
        "arn:aws:s3:::mybucket/*"
      ]
    }]
    

Related Articles