有时压测时,需要从日志文件中提取每行指定字段的值(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 = "";
String key = "S_KEYWORD_COMPLETE_NEW=";
try {
while ((b = br.readLine()) != null ) {
sb.append(b);
String strOld = sb.toString();
//截取从每行起始标识开始,到行末这块字符串
String strNew = strOld.substring(strOld.indexOf(key) + key.length(), strOld.length());
//截取从每行起始位置到结束标识这段字符串
String strOk = strNew.substring(0, strNew.indexOf("&"));
//转码为汉字
String strOkDecode = java.net.URLDecoder.decode(strOk, "UTF-8");
//写入文件并换行
bw.write(strOkDecode + "\n");
//清空数据
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();
}
}
}