Java Paths.get & hellip; readAllBytes (path)) does not work with the relative path


I am new to Java and trying to build an FX application. One of my function aims at replacing certain strings with others. The script works fine as long as I define the absolute path of the target file, but breaks when I work with the relative path.

The problem is in the method "readAllBytes", that only works with the complete path. But I need relative path, since the folder location will vary.

The target file is in the project folder. Is there any other method I can use to read the file content, that does not require the absolute path?

Thanks a lot in advance. Below is the snippet:

    if (checkbox.isSelected()) {
        //this works .....
        Path path = Paths.get("//home/../../../../Target.fxml")
        Charset charset = StandardCharsets.UTF_8;
        String content = new String(Files.readAllBytes(path));
        content = content.replaceAll("text_old" , "text_new");
        Files.write(path, content.getBytes(charset));

        //this doesn't work...
        Path path = Paths.get("Target.fxml");

Caused by: java.nio.file.NoSuchFileException: Target.fxml

The exception root cause java.nio.file.NoSuchFileException: Target.fxml does mean that the file does not exist at the given location.

If you're doing Paths.get("Target.fxml") you are looking in the current working directory for the file Target.fxml. But since the file is located in src/javafxapplication/Target.fxml and the program is run from a different directory Target.fxml can not be found.

You can check the working directory of your application using e.g.:


This might very well be the classes directory. If you want to e.g. point from classes to the src folder you can use the following path:


This is however bad practice since the src folder is normally not part of your distribution package. You should probably copy the Target.fxml to another location or use Build Tools like Apache Maven to create a jar file which does include the Target.fxml and read the contents from the jar file using ClassLoader.getResource().