需求:找到每个文件下以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.附带文件路径的打印,方便检阅
等等