如何使用Java中的ClassPathResource访问Maven Project中的文本文件?

时间:2015-10-26 10:06:12

标签: java maven

我正在尝试使用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)

Here is the structure of Maven project directory

2 个答案:

答案 0 :(得分:0)

尝试ClassPathResource resource = new ClassPathResource("com/thesis/work/raw_sentences.txt");

答案 1 :(得分:0)

他们都是对的。

假设有java个文件com/a/b/App.java,资源目录为com/a/b/test.test

然后,

两个

ClassPathResource resource = new ClassPathResource("/com/a/b/test.dat");

ClassPathResource resource = new ClassPathResource("test.dat");

应该没问题。

深层原因是,maven会将资源内容复制到target/classes/

因此,test.datApp.class位于同一目录中,test.dat/com/a/b/test.dat都是正确的。

以下是target中的文件结构:

  target
    |__
     classes
        └── a
            └── b
                |__
                   test.dat
                   App.class