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

寵の児 提交于 2019-12-02 22:03:26

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/41275278/java-paths-get-readallbytespath-not-working-with-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!