How to define a relative path in java

JavaRelative Pathjdk1.6

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

 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

Solution 4 - Java

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

Solution 5 - Java

 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");

Solution 6 - Java

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);

Solution 7 - Java

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();

Solution 8 - Java

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."

Solution 9 - Java

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 \.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionishkView Question on Stackoverflow
Solution 1 - JavaVinay VeluriView Answer on Stackoverflow
Solution 2 - JavahoaphamView Answer on Stackoverflow
Solution 3 - JavaAbin Manathoor DevasiaView Answer on Stackoverflow
Solution 4 - JavaDanonView Answer on Stackoverflow
Solution 5 - JavayahiteshView Answer on Stackoverflow
Solution 6 - JavaChris ListonView Answer on Stackoverflow
Solution 7 - JavaKirill ChView Answer on Stackoverflow
Solution 8 - JavaChristophe RoussyView Answer on Stackoverflow
Solution 9 - JavaMaciej KrzyżyńskiView Answer on Stackoverflow