【发布时间】:2015-10-26 10:06:12
【问题描述】:
我正在尝试使用 Maven java 项目中的“ClassPathResource”访问文件“raw_sentences.txt”文件。我的文件位于“\src\main\resources\com\thesis\work\raw_sentences.txt”中。我尝试了很多方法,但它总是返回错误 NullPointerExcepetion。我可以从
访问该文件文件 testf = new File(obj.getClass().getResource("raw_sentences.txt").toURI());
但是 ClassPathResrouce 不工作,我不知道为什么,请帮忙!
package com.thesis.work;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.core.io.ClassPathResource;
public class App
{
static final Logger logger = Logger.getLogger("MyLog");
public static void main( String[] args ) throws IOException, URISyntaxException
{
App obj = new App();
File testf = new File( obj.getClass().getResource( "raw_sentences.txt" ).toURI() );
logger.log(Level.INFO, "File: ", testf.getPath()); // Works!
logger.log(Level.INFO, "Load data...\n");
ClassPathResource resource = new ClassPathResource("raw_sentences.txt");
logger.log(Level.INFO, "File loaded : ", resource.getPath()); // not Working!
}
static void print(String nd){
System.out.println(nd);
}}
Exception in thread "main" java.io.FileNotFoundException: class path resource [raw_sentences.txt] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) at com.thesis.work.App.main(App.java:24)
【问题讨论】: