最近写了一个JavaFX小程序,需要能够动态的修改配置文件。但是发现两个问题:
1)打包后有一些资源文件比如word、excel没法读取
2)配置文件如果在打的jar包内,则没法进行修改
我自己解决方法是:将配置文件移到jar包同一个文件夹内,然后先通过虚拟机获取jar包位置后,再获取配置文件的路径

获取路径的代码,我是看这篇文章的。
具体代码如下,包含两个类:

public class YamlUtils {
    private static final String PATH = PathUtils.getJarParentPath() + "path.yaml";
    public static PathConfiguration getPathConfiguration() throws FileNotFoundException {
        Yaml yaml = new Yaml();
        FileReader fileReader = new FileReader(PATH);
        return yaml.load(fileReader);
    }
    public static void savePathConfiguration(String pendingDirectoryPath, String targetDirectoryPath) throws IOException {
        PathConfiguration pathConfiguration = new PathConfiguration(pendingDirectoryPath, targetDirectoryPath);
        Yaml yaml = new Yaml();
        FileWriter fileWriter = new FileWriter(PATH);
        yaml.dump(pathConfiguration, fileWriter);
    }
}


public class PathUtils {
    public static String getJarParentPath() {
        String path = System.getProperty("java.class.path");
        int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1;
        int lastIndex = path.lastIndexOf(File.separator) + 1;
        return path.substring(firstIndex, lastIndex);
    }
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐