![](/img/trans.png)
[英]How to load external file using ClassPathResource in Spring?
[英]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)
嘗試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.dat
與App.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.