有时压测时,需要从日志文件中提取每行指定字段的值(S_KEYWORD_COMPLETE_NEW字段),如下:
?S_KEYWORD_COMPLETE_NEW=%E7%94%9F%E4%BA%A7&NewId=60773611
截取策略:以 "S_KEYWORD_COMPLETE_NEW="为开头标识,以"S_KEYWORD_COMPLETE_NEW="字段值后第一个"&"为结束。
以下为具体java代码
import java.io.*;
/**
* @Author: jiajun.du
* @Date: 2021/8/3 18:00
*/
public class ExtractFieldValues {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\50.130\\onlyuri.log"), "GB2312"));//源日志文件
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\50.130\\onlyuri.txt"), "GB2312"));//存放截取值的新文件
StringBuffer sb = new StringBuffer();
String b = "";
int num =0;//读取行数控制
try {
while ((b = br.readLine()) != null && num <80000) {
sb.append(b);
String s = sb.toString();
String strNew = s.substring(s.indexOf("S_KEYWORD_COMPLETE_NEW=") + 23, s.length());//每行截取起始标识
String key = strNew.substring(0, strNew.indexOf("&"));//每行截取结束标识
//String keyNew = unicodeToString(key);
bw.write(key+"\n");//写入文件并换行
num++;
sb.delete(0,sb.length());//清空数据
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
e.printStackTrace();
}
}
}