Java有规则的提取文件内信息(key:value)

需求:找到每个文件下以conf结尾的文件内的server-name对应的值(包括文件夹下的文件夹里以conf结尾的文件),注释掉的不用

#可以举一反三,最主要的是提取文件内有规律的数据。

package com;

import java.io.*;

/**
 * Created by PJB on 2020/9/2.
 */
public class Bianli {
    public static String filename = "";
    public static void main(String[] args) throws Exception {
        String inPath = "C:\\Users\\PJB\\Desktop\\resource\\conf";
        String outPath = "C:\\Users\\PJB\\Desktop\\resource\\result.txt";
        File file = new File(inPath);
        //待读取文件或文件夹,文件后缀,文件内容key,输出文件路径
        forFile(file,"conf","server_name",outPath);
    }
    public static void forFile(File file,String lastStr,String contains,String outPath) throws Exception {
        File[] files = file.listFiles();
        for (File f:files){
            if (f.isDirectory()){
                forFile(f,lastStr,contains,outPath);
            }
            filename = f.getName();
            if (f.isFile()&&(filename.substring(filename.lastIndexOf(".")+1)).equals(lastStr)){
                //System.out.println(f.getAbsoluteFile());
                InputStreamReader reader = new InputStreamReader(new FileInputStream(f),"UTF-8");
                BufferedReader bufferedReader = new BufferedReader(reader);
                String line = "";
                while((line = bufferedReader.readLine())!=null){
                    if (line.startsWith("#")){
                        continue;
                    }
                    if (line.contains(contains)){
                        String string = line.substring(line.indexOf(contains)+contains.length()).trim();
                        System.out.println(string);
                        writeToTXT(string,outPath);
                    }
                }
            }
        }
    }
    public static void writeToTXT(String str,String path) throws Exception{
        FileOutputStream o = null;
        byte[] buff = new byte[]{};
        File file = new File(path);
        if (!file.exists()){
            file.createNewFile();
        }
        buff = str.getBytes();
        o = new FileOutputStream(file,true);
        o.write(buff);
        o.flush();
        o.close();
    }
}

有了这个模板之后,想要加入或者是修改功能就容易多了。

例如:

1.不检索后缀或者检索多种后缀

2.检索两种key并且以key:value 形式打印

3.附带文件路径的打印,方便检阅

等等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值