How to read a file in AWS Lambda Function written in Java ?

前端 未结 4 494
庸人自扰
庸人自扰 2021-02-04 15:24

I have written an AWS Lambda Handler as below :

package com.lambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.r         


        
4条回答
  •  庸人自扰
    2021-02-04 16:08

    I have made following changes in my code and now its works perfect :

    Majorly changed following two lines :

    ClassLoader classLoader = getClass().getClassLoader();

    File cityFile = new File(classLoader.getResource("City.db").getFile());

    package com.lambda;
    
    
    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.LambdaLogger;
    import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
    import java.io.*;
    
    public class TestDetailsHandler implements RequestStreamHandler {
    
    
        public void  handleRequest(InputStream input,OutputStream output,Context context){
    
            // Get Lambda Logger
            LambdaLogger logger = context.getLogger();
    
            // Receive the input from Inputstream throw exception if any
    
            ClassLoader classLoader = getClass().getClassLoader();
    
            File cityFile = new File(classLoader.getResource("City.db").getFile());
            FileInputStream fis = null;
    
            try {
                fis = new FileInputStream(cityFile);
    
                System.out.println("Total file size to read (in bytes) : "
                        + fis.available());
    
                int content;
                while ((content = fis.read()) != -1) {
                    // convert to char and display it
                    System.out.print((char) content);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null)
                        fis.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    

提交回复
热议问题