How to define a relative path in java

ishk picture ishk · Jan 8, 2013 · Viewed 242.6k times · Source

Here is the structure of my project :

here is the structure of my project

I need to read config.properties inside MyClass.java. I tried to do so with a relative path as follows :

// Code called from MyClass.java
File f1 = new File("..\\..\\..\\config.properties");  
String path = f1.getPath(); 
prop.load(new FileInputStream(path));

This gives me the following error :

..\..\..\config.properties (The system cannot find the file specified)

How can I define a relative path in Java? I'm using jdk 1.6 and working on windows.

Answer

VinayVeluri picture VinayVeluri · Jan 8, 2013

Try something like this

String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");

So your new file points to the path where it is created, usually your project home folder.

[EDIT]

As @cmc said,

    String basePath = new File("").getAbsolutePath();
    System.out.println(basePath);

    String path = new File("src/main/resources/conf.properties")
                                                           .getAbsolutePath();
    System.out.println(path);

Both give the same value.