Java Paths.get … readAllBytes(path)) not working with relative path

…衆ロ難τιáo~ 提交于 2019-12-02 09:36:42

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

System.out.println(System.getProperty("user.dir")));

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:

Paths.get("../src/javafxapplication/Target.fxml")

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

Got it working after all, thanks to Fasseg and others who found the time and patience to look into this. Here is the final code:

        Path path = Paths.get("src/javafxapplication2/PopupFXML.fxml");
        Charset charset = StandardCharsets.UTF_8;
        String content = new String(Files.readAllBytes(path));
        content = content.replaceAll("old_text" , "new_text");
        Files.write(path, content.getBytes(charset));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!