要求properties配置文件中路径分割符为反斜杠‘\‘时,读取处理

Java在Java中关于路径中斜杠与反斜杠的使用可以在下面了解下:
https://blog.csdn.net/haizhongyun/article/details/7427162

有这样一个需求:方便Windows用户在配置文件中手动更改选择文件路径
大家都知道Windows中路径都是类似于:C:\Windows\Boot反斜杠路径,而反斜杠在Java中的存在表示转移字符。见惯了程序中的//双斜线、/单斜线、\双反斜线,都能够识别路径,但唯独\反斜线不行。

在要求配置文件中路径为'\',配置文件为properties属性类存储时处理如下:

  • 配置文件config.properties内容:
#这是一个测试案例
testFile01Path=D:\Download\AppGallery\VMware

testFile02Path=D:\Download\AppGallery\Navicat for MySQL

测试程序:

package org.example;

import java.io.*;
import java.util.Objects;
import java.util.Properties;

/**
 * 此项目仅为Maven项目:
 * properties文件的"\"默认为转义字符,properties文件要求中加载路径地址为"\"反斜杠时处理:
 * 方法:重载Propertiess属性类,重写load方法
 * */

public class Demo extends Properties {
    /**
     * 重写Properties的load方法,更换配置文件中的‘\’为‘/’
     * */
    @Override
    public synchronized void load(Reader reader) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(reader);
        while (true) {
            //缓冲流以行读取数据
            String line = bufferedReader.readLine();
            if (Objects.isNull(line)) {
                break;
            }
            //注意: properties属性类文件存在第一个隐藏字符,需要删除掉,否则第一个数据以key查找不存在
            if (line.startsWith("\uFEFF")) {
                line = line.substring(1);
            }
            //如果是#注释内容,则不做操作
            if (line.startsWith("#") || line.isEmpty()) {
            }else {
                //将读取的数据格式为’=‘分割,以key,Value方式存储properties属性类文件数据
                String[] split = line.split("=");
                //由于‘\’在Java中表示转义字符,需要将读取的路径进行转换为‘/’符号,这里“\\\\”代表一个‘\’
                put(split[0], split[1].replaceAll("\\\\", "/"));
            }
        }
    }
    public static void main(String[] args) throws IOException {
        Demo demo = new Demo();
        //加载配置文件位置
        demo.load(new InputStreamReader(new FileInputStream("src/main/resources/config.properties")));
        String testFile01Path = demo.getProperty("testFile01Path");
        String testFile02Path = demo.getProperty("testFile02Path");

        System.out.println("testFile01Path:" + testFile01Path);
        System.out.println("testFile02Path:" + testFile02Path);
    }
}

在这里插入图片描述

posted @ 2022-09-23 11:42  辰臣  阅读(53)  评论(0)    收藏  举报  来源