60

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.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
ishk
  • 1,873
  • 5
  • 19
  • 22
  • 3
    That is a valid relative path in Windows .. but you're not where you link you are. (Hint, it's relative from the **current working directory** and not the source file.) –  Jan 08 '13 at 06:09
  • You should keep your `config.properties` under `src`. Create `config` package under `src`, keep `config.properties` under `config` package. And access simply it as `config/config.properties`. – Nandkumar Tekale Jan 08 '13 at 06:26
  • 1
    Will `config.properties` be distributed with the Jar? If so it becomes an [tag:embedded-resource] which is not accessible by `File`, but must instead be accessed by `URL`. – Andrew Thompson Jan 08 '13 at 06:30
  • yes it distribute with the jar file – ishk Jan 08 '13 at 07:21

9 Answers9

95

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.

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
7

Firstly, see the different between absolute path and relative path here:

An absolute path always contains the root element and the complete directory list required to locate the file.

Alternatively, a relative path needs to be combined with another path in order to access a file.

In constructor File(String pathname), Javadoc's File class said that

A pathname, whether abstract or in string form, may be either absolute or relative.

If you want to get relative path, you must be define the path from the current working directory to file or directory.Try to use system properties to get this.As the pictures that you drew:

String localDir = System.getProperty("user.dir");
File file = new File(localDir + "\\config.properties");

Moreover, you should try to avoid using similar ".", "../", "/", and other similar relative to the file location relative path, because when files are moved, it is harder to handle.

Betty
  • 237
  • 6
  • 16
hoapham
  • 180
  • 5
  • 10
4
 File f1 = new File("..\\..\\..\\config.properties");  

this path trying to access file is in Project directory then just access file like this.

File f=new File("filename.txt");

if your file is in OtherSources/Resources

this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder
Abin Manathoor Devasia
  • 1,945
  • 2
  • 21
  • 47
  • how do i write relative path here? – ishk Jan 08 '13 at 06:23
  • @ishk i dont know whether java support relative access through the packages,we can access files from project directory like i say above, and access subfolders too.like File f=new File("folder/filename.txt"); – Abin Manathoor Devasia Jan 08 '13 at 06:31
2

It's worth mentioning that in some cases

File myFolder = new File("directory"); 

doesn't point to the root elements. For example when you place your application on C: drive (C:\myApp.jar) then myFolder points to (windows)

C:\Users\USERNAME\directory

instead of

C:\Directory
Danon
  • 2,771
  • 27
  • 37
1
 public static void main(String[] args) {
        Properties prop = new Properties();
        InputStream input = null;
        try {
            File f=new File("config.properties");
            input = new FileInputStream(f.getPath());
            prop.load(input);
            System.out.println(prop.getProperty("name"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

You can also use
Path path1 =FileSystems.getDefault().getPath(System.getProperty("user.home"), "downloads", "somefile.txt");

yahitesh
  • 83
  • 8
1

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
Chris Liston
  • 155
  • 2
  • 9
1

Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:

resources/wsdl/WebServiceFile.wsdl

To get the path from some method to this file you can do the following:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();
Kirill Ch
  • 5,496
  • 4
  • 44
  • 65
0

Since Java 7 you have Path.relativize():

"... a Path also defines the resolve and resolveSibling methods to combine paths. The relativize method that can be used to construct a relative path between two paths."

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
0

If the file, as per your diagram, is 2 levels above your src folder, you should use the following relative path:

../../config.properties

Please note, that in relative paths we use forward slashes / and not backslashes \.

Roger
  • 1,004
  • 2
  • 12
  • 24