How to define a relative path in java
Asked Answered
I

9

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.

Insufficient answered 8/1, 2013 at 6:1 Comment(4)
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.)Trefoil
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.Tiltyard
Will config.properties be distributed with the Jar? If so it becomes an embedded-resource which is not accessible by File, but must instead be accessed by URL.Prospector
yes it distribute with the jar fileInsufficient
T
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.

Tremblay answered 8/1, 2013 at 6:8 Comment(1)
When creating File("") this way, the parameter should be the path to the file in your project, instead of "".Retrogress
W
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.

Wame answered 28/1, 2018 at 4:27 Comment(0)
L
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
Langton answered 8/1, 2013 at 6:15 Comment(2)
how do i write relative path here?Insufficient
@Insufficient 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");Langton
W
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
Walkling answered 28/1, 2015 at 21:59 Comment(0)
F
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");

Finer answered 18/8, 2015 at 9:43 Comment(0)
T
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);
Thermograph answered 10/3, 2017 at 16:40 Comment(0)
W
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();
Witten answered 14/2, 2018 at 15:24 Comment(0)
C
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."

Catherincatherina answered 27/9, 2021 at 7:34 Comment(0)
W
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 \.

Wendeline answered 3/10, 2021 at 7:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.