2017-05-09 111 views
0

我想读取我的Spring引导控制台应用程序的资源文件夹中的文件,但我收到文件未找到异常。无法从弹簧引导罐中读取文本文件

这里是我的POM

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

这里是例外:

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- INF/classes文件夹。

感谢, -dj

+0

如何你想读什么书? – pvpkiran

+0

我忘记提及我正在使用ClassPathResource。 ClassPathResource resource = new ClassPathResource(len +“.txt”); File file = resource.getFile(); –

回答

4

这是春天开机,让我们使用使用ClassPathResource

@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 file = resource.getFile(); –

+0

@desiJoe我已经更新了我的答案 –

0

这对我有用!

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

哪里,因为这没有工作

ClassPathResource resource = new ClassPathResource(len + ".txt"); 
File file = resource.getFile();