背景:将项目部署到linux服务器后,忘记路径分隔符兼容问题
这是关于获取系统文件分割符的方法 Linux的分隔符是 / Windows的则是 \
//获取当前系统得文件分割符
//(因为在Windows和Linux系统的文件分隔符是不一样的有时候需要用到这个方法解决)
System.getProperties().getProperty("file.separator");
下面是获取配置文件的配置的方法:
try {
Properties properties = new Properties();
//直接获取配置文件路径 不需要知道配置文件路径 也同时解决了Win和linux系统兼容问题
String path = ClassName.class.getClassLoader().getResource("配置文件名").getPath();
//读取配置文件 只需要将获取的文件路径放进去即可
InputStream in = new BufferedInputStream(new FileInputStream(path));
//加载属性
properties .load(in);
} catch (Exception e) {
e.printStackTrace();
}
Windows环境下获取配置文件绝对路径:
String path=this.getClass().getClassLoader().getResource("配置文件.xml").getPath();
或者:
URL url = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX + "配置文件.xml");