I am trying to access file "raw_sentences.txt" file using "ClassPathResource" in Maven java project. My file is located in the "\\src\\main\\resources\\com\\thesis\\work\\raw_sentences.txt". I have tried many ways but it always returning with an error NullPointerExcepetion. I can access the file from
File testf = new File( obj.getClass().getResource( "raw_sentences.txt" ).toURI() );
But ClassPathResrouce is not working i don't know why, please help!
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)
尝试ClassPathResource resource = new ClassPathResource("com/thesis/work/raw_sentences.txt");
They both shall be right.
Suppose there is the java
file com/a/b/App.java
, and the resource directory is com/a/b/test.test
.
Then,
both
ClassPathResource resource = new ClassPathResource("/com/a/b/test.dat");
and
ClassPathResource resource = new ClassPathResource("test.dat");
should be fine.
The deep reason is that, maven
would copy the contents of resource to target/classes/
.
Therefore, the test.dat
is in the same directory with App.class
, and test.dat
or /com/a/b/test.dat
both are right.
Here is the file structure in target
:
target
|__
classes
└── a
└── b
|__
test.dat
App.class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.