簡體   English   中英

如何使用Java中的ClassPathResource訪問Maven Project中的文本文件?

[英]How to access text file in Maven Project using ClassPathResource in Java?

我正在嘗試在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)

這是Maven項目目錄的結構

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

他們倆都是正確的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM