2017-05-09 6 views
0

私のSpringブートコンソールアプリケーションのresourcesフォルダにあるファイルを読み込もうとしていますが、ファイルが見つかりませんでした。スプリングブートジャーからテキストファイルを読み取ることができません

java.io.FileNotFoundException: class path resource [9.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/abc/Documents/workspace-sts-3.8.4.RELEASE/xyz/target/xyz-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/9.txt 

私はXYZ-0.0.1-SNAPSHOT.jarにファイルを開いて、9.txtがBOOT-である:ここ

は私のポンポン

<resource> 
    <directory>src/main/resources</directory> 
    <includes> 
     <include>**/*.*</include> 
    </includes> 
    </resource> 

そして、ここでは例外でありますINF/classesフォルダにあります。それは春ブーツだ、のはClassPathResourceを使ってみましょう -dj

+0

はどのようにあなたが読んしようとしている動作しませんでしたか? – pvpkiran

+0

ClassPathResourceを使用していたことを忘れてしまいました。 ClassPathResource resource = newクラスパスリソース(len + ".txt");ファイルfile = resource.getFile(); –

答えて

4

おかげで、

@Component 
public class MyBean { 
    @Value("9.txt") 
    private ClassPathResource resource; 

    @PostConstruct 
    public void init() throws IOException { 
     Files.lines(resource.getFile().toPath(), StandardCharsets.UTF_8) 
      .forEach(System.out::println); 
    } 
} 

更新:クラスパスリソースがファイル内にある場合ClassPathResource以来はjava.io.Fileのように解像度をサポートしていますシステムではなく、JAR内のリソースでは使用しないでください。

@Component 
public class MyBean { 
    @Value("9.txt") 
    private ClassPathResource resource; 

    @PostConstruct 
    public void init() throws IOException { 
     try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) { 
      bufferedReader.lines() 
       .forEach(System.out::println); 
     }   
    } 
} 
+0

私はClassPathResourceを使用していたことを忘れていました。 \t \t \t ClassPathResource resource = new ClassPathResource(len + ".txt"); ファイルfile = resource.getFile(); –

+0

@desiJoe私は自分の答えを更新しました –

0

これは私のために働いている!

InputStream in = this.getClass().getResourceAsStream("/" + len + ".txt"); 

ところ、このよう

ClassPathResource resource = new ClassPathResource(len + ".txt"); 
File file = resource.getFile(); 
関連する問題