【问题标题】:How to access text file in Maven Project using ClassPathResource in Java?如何使用 Java 中的 ClassPathResource 访问 Maven 项目中的文本文件?
【发布时间】: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)

【问题讨论】:

    标签: java maven


    【解决方案1】:

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

    【讨论】:

    • 谢谢,实际上我没有使用过 maven 项目。我可以只使用文件名吗?
    【解决方案2】:

    他们都应该是对的。

    假设有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
    

    【讨论】:

    • 我的情况不是这样,ClassPathResource resource = new ClassPathResource("com/thesis/work/raw_sentences.txt"); //作品! ClassPathResource resource = new ClassPathResource("raw_sentences.txt");//不工作
    猜你喜欢
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 2011-04-22
    • 2016-05-31
    • 1970-01-01
    • 2013-02-23
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多