Reputation: 865
I have spring project. My file here: /src/main/java/resources/file.txt.
How I can get full path of this?
If I run from test it works:
String path = System.getProperty("user.dir") + "/src/main/java/resources/file.txt";
But if I use tomcat, it shows another path inside tomcat folder. So spring cannot find this path.
EDIT: this.getClass().getClassLoader().getResource("file.txt") is null
UPDATED: sorry for stupid question. It works, I set wrong name of file.
Upvotes: 4
Views: 29454
Reputation: 420
The relative path depends on the current context context: Application, library,....
You can dig documentation or simply add something like
File fn = new File("resources/database.db");
logger.info(fn.getAbsolutePath());
To see where the current path is in that moment.
For example, to create SQLite datasource in the Spring @Configuration block
@Configuration
.....
@Bean
....
String dbName="database.sqlite";
File fn = new File("src/main/resources/"+dbName);
String name=fn.toURI().toString();
dataSourceBuilder.url("jdbc:sqlite:"+name );
....
Upvotes: 2
Reputation: 24561
With Spring you can use class ClassPathResource
. It can read files from java classpath without too much pure Java boilerplate code.
Upvotes: 0
Reputation: 41200
As file - file.txt
is in resources directory, normally this would be copied to class-path
by build process(tool like Maven, Gradle). And this would easy with to load file with relative path.
This thread had extensively talked about how to load file from class-path
.
How to really read text file from classpath in Java
Upvotes: 4