2

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.

annoirq
  • 825
  • 5
  • 18
  • 30

3 Answers3

3

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

Community
  • 1
  • 1
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

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 );
....
RSG
  • 384
  • 3
  • 7
0

With Spring you can use class ClassPathResource. It can read files from java classpath without too much pure Java boilerplate code.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92