2016-04-06 4 views
2

私は以下のようにAWSラムダハンドラを書かれている:AWSでファイルを読む方法ラムダ関数はJavaで書かれていますか?

enter image description here

:でも、私は以下を参照してくださいどこにでもに抑え、City.db、リソースフォルダ内の利用可能:

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 

     File starting = new File(System.getProperty("user.dir")); 
      System.out.println("Source Location" + starting); 

      File cityFile = new File(starting + "City.db"); 
     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(); 
      } 
     } 
    } 

} 

そのファイルを読み込みますしかし、このラムダ関数の実行に関する次のメッセージを表示しています。

START RequestId: 5216ea47-fc43-11e5-96d5-83c1dcdad75d Version: $LATEST 
Source Location/ 
java.io.FileNotFoundException: /city.db (No such file or directory) 
    at java.io.FileInputStream.open0(Native Method) 
    at java.io.FileInputStream.open(FileInputStream.java:195) 
    at java.io.FileInputStream.<init>(FileInputStream.java:138) 
    at com.lambda.TestDetailsHandler.handleRequest(TestDetailsHandler.java:26) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:497) 
    at lambdainternal.EventHandlerLoader$StreamMethodRequestHandler.handleRequest(EventHandlerLoader.java:511) 
    at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:972) 
    at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:231) 
    at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:59) 
    at java.lang.Class.forName0(Native Method) 
    at java.lang.Class.forName(Class.java:348) 
    at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:93) 
END RequestId: 5216ea47-fc43-11e5-96d5-83c1dcdad75d 
REPORT RequestId: 5216ea47-fc43-11e5-96d5-83c1dcdad75d Duration: 58.02 ms Billed Duration: 100 ms  Memory Size: 1024 MB Max Memory Used: 50 MB 

pom.xmlファイルの3210本の

内容:

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>com.lambda</groupId> 
    <artifactId>testdetails</artifactId> 
    <version>1.0-SNAPSHOT</version> 
    <packaging>jar</packaging> 
    <name>test-handler</name> 

    <dependencies> 
     <dependency> 
      <groupId>com.amazonaws</groupId> 
      <artifactId>aws-lambda-java-core</artifactId> 
      <version>1.1.0</version> 
     </dependency> 

     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.11</version> 
      <scope>test</scope> 
     </dependency> 



     </dependencies> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-shade-plugin</artifactId> 
       <version>2.3</version> 
       <configuration> 
        <createDependencyReducedPom>false</createDependencyReducedPom> 
       </configuration> 
       <executions> 
        <execution> 
         <phase>package</phase> 
         <goals> 
          <goal>shade</goal> 
         </goals> 
        </execution> 
       </executions> 
      </plugin> 
     </plugins> 
    </build> 
</project> 

私はここにあるファイルを維持するためのさまざまな方法を使用していたが、最後にそのは動作していません。ここで間違っていることを教えてください。

しかし、xyz.propertiesファイルをresourcesフォルダに保存し、PropertyManagerファイルから読み込んだ別のプロジェクトでは、正常に動作しています。私は私のシステム上でそれを正常に動作してテストしましたが、AWS Lambda機能では動作しません。

+0

これはほんの数分前に尋ねた質問の複製です:http://stackoverflow.com/questions/36462933/how-to-read-s3-file-from-aws-lambda-function-written- in-javaあなたはその質問で回答を受け取りましたが、あなたが提供したソリューションを使用していないコードを投稿しました。 –

+0

@マーク、これは別の質問です。以前は、S3からファイルを読み込むことに関連していました。この質問は、JARパッケージ内のファイルの読み込みに関連しています。 –

+0

申し訳ありません、私はあなたが同じ質問をしていると思ったので、同じファイル名を読もうとしています。 –

答えて

4

私は私のコードと、今その作品完璧に以下の変更を行っています

すぎなかった2行以下の変更:。

のClassLoaderクラスローダ=はgetClass()のgetClassLoader();

ファイル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(); 
      } 
     } 
    } 

enter image description here

+0

代わりにgetaresourceAsStream()を使用してください。すべての場合に機能しないファイルに変換する必要はありません。 – eckes

1

これはのは、このプロジェクトの構造がどのように見えるかであるとしましょう、私はそれをやった方法です -

enter image description here

そして、あなたはファイル設定を読みたいです.propertiesは、project-dir/resourcesディレクトリ内にあります。

になり、ファイルの内容を読み込むためのコード -

InputStream input = null; 
try { 
    Path path = Paths.get(PropertyUtility.class.getResource("/").toURI()); 

    // The path for config file in Lambda Instance - 
    String resourceLoc = path + "/resources/config.properties"; 

    input = new FileInputStream(resourceLoc); 
} catch(Exception e) { 
    // Do whatever 
} 

あなたはこのプロジェクトの構造を以下のこのコードを使用している場合、それはAWSラムダで動作します。

PropertyUtilityは、設定ファイルの内容を読み込むために作成したユーティリティクラスです。 PropertyUtilityクラスには、次のようになります -

enter image description here

あなたは上記のコードで見ることができるように、設定ファイルのパスは、ローカルシステム内およびラムダインスタンスで異なっています。プロジェクトディレクトリを指すようにするために、あなたがpath.getParentを(しなければならない理由があるビン

ローカルマシンで

PropertyUtility.class.getResource(「/」)ポイント、)、この例ではHelloLambdaです。

ラムダインスタンスの場合、PropertyUtility.class.getResource( "/")は、project-directoryを直接指します。

0

resourcesディレクトリの下に配置内のファイルには、次のソリューションが動作する必要がある場合:

String fileName = "resources/config.json"; 

Path path = Paths.get(this.getClass().getResource("/").toURI()); 
Path resourceLocation = path.resolve(fileName); 

try(InputStream configStream = Files.newInputStream(resourceLocation)) { 
      //use your file stream as you need. 
} 

ここで最も重要な部分は、「リソース/ config.json」で、それは/「/リソースであってはなりませんconfig.json "、ファイルの場所はlambdaの/var/task/resources/config.jsonなので、チェックしました。

これは、aws lambdaでファイルを読む際にまだ問題に直面している人に役立ちます。

関連する問題