java中读取sourceFolder下的配置文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cpp1781089410/article/details/81189356

读取文件常用两种方法:

1.通过绝对路径读取文件

2.使用相对路径读取文件,实际是通过类加载路径获取到文件的绝对路径。

public class FilePathAfterCompile {
    @Test
    public void test() {
        String path = getFilePathInSrcAfterRun();
        System.out.println("编译之后的src路径:" + path);
        String filePath = path + "test.properties";
        System.out.println("编译之后src下的文件路径:" + filePath);
        // 打印配置文件
        printProperties(filePath);
        // 使用显示路径
        printProperties("D:/workspace2/test1/bin/test.properties");
    }

    public String getFilePathInSrcAfterRun() {
        String path = this.getClass().getClassLoader().getResource("").toString();
        System.out.println("编译后src路径:" + path);
        int m = path.indexOf("/");
        // 在系统中的绝对路径
        path = path.substring(m + 1);// 从反斜杠之后的一位开始截取字符串
        System.out.println("编译后src路径:" + path);
        return path;
    }

    public void printProperties(String filePath) {
        // Properties相当于只能存放String类型的键值对
        Properties properties = new Properties();
        try {
            InputStream inStream = new BufferedInputStream(new FileInputStream(filePath));
            properties.load(inStream);
            System.out.println(properties);
            Set<String> keys = properties.stringPropertyNames();
            // 读取配置
            for (Iterator<String> it = keys.iterator(); it.hasNext();) {
                String key = it.next();
                String value = properties.getProperty(key);
                System.out.println("key=\t" + key + "\tvalue=" + value);
            }
        } catch (IOException e) {
        }
    }
}

猜你喜欢

转载自blog.csdn.net/cpp1781089410/article/details/81189356
今日推荐