前端之家收集整理的这篇文章主要介绍了
正则读写文件匹配,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BrasBD {
public static void writesqlIntoFile(BufferedWriter bw,String ipAddr){
System.out.println(ipAddr);
try {
bw.write(ipAddr);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<String[]> getBrasIP(String path) {
FileInputStream fis;
BufferedReader br;
InputStreamReader isr;
String line="";
List<String[]> l=new ArrayList<String[]>();
try {
fis = new FileInputStream(path);
isr=new InputStreamReader(fis,"GBK");
br = new BufferedReader(isr);
//循环读取每一行
while ((line=br.readLine())!=null) {
line=line.trim();
//正则表达式 section 1 110.85.137.1 110.85.137.254
Pattern p = Pattern.compile("(section)\\s+(\\d)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)");
// 操作的字符串
Matcher m = p.matcher(line);
//根据正则表达式查找
while (m.find()) {
System.out.println(m.group(1)+"-------"+m.group(2)+"-------"+m.group(3)+"-------"+m.group(4));
l.add(new String[]{m.group(3),m.group(4)});
}
}
br.close();
isr.close();
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(l.size());
//
// for (String[] strings : l) {
// System.out.println(strings[0]+" "+strings[1]);
// }
return l;
}
public static List<String> buildsql(List<String[]> l,String BrasIP){
List<String> sqlList=new ArrayList<String>();
String s="";
String s1="insert into T_SDX_INFO values(" ;
String s2="110085181002,110085181254" ;
// String s3=",'218.5.204.119','0596',990600,2,'sdxPort=2000,secret=testing123',0);";
String s3=",'" +BrasIP+
"',0);";
for (String[] strings : l) {
String B="";
String E="";
//========开始=======================
String[] b=strings[0].split("\\.");
for (int i=0;i<4;i++) {
if(b[i].length()==1)
b[i]="00"+b[i];
if(b[i].length()==2)
b[i]="0"+b[i];
B=B+b[i];
}
//=========结束======================
String[] e=strings[1].split("\\.");
for (int i=0;i<4;i++) {
if(e[i].length()==1)
e[i]="00"+e[i];
if(e[i].length()==2)
e[i]="0"+e[i];
E=E+e[i];
}
s2=B+","+E;
s=s1+s2+s3;
System.out.println(s);
sqlList.add(s);
}
return sqlList;
}
public static void main(String[] args) throws IOException {
List<String[]> l=getBrasIP("C:\\Users\\hugsh\\Desktop\\BrasIP-113.txt");
List<String> sqlList=buildsql(l,"218.5.204.113");
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("C:\\Users\\hugsh\\Desktop\\BrasIP-113.sql")));
for (String string : sqlList) {
writesqlIntoFile(bw,string);
}
bw.flush();
bw.close();
}
}