从文本中读取指定的列插到另一个文本
问题:如果一个文本中有如下内容 a b c d .....e..... a1 b1 c1 d1 .....e1..... a2 b2 c2 d2 .....e2..... a3 b3 c3 d3 .....e3..... a4 b4 c4 d4 .....e4..... a5 b5 c5 d5 .....e5..... a6 b6 c6 d6 .....e6..... a7 b7 c7 d7 .....e7..... a8 b8 c8 d8 .....e8..... a9 b9 c9 d9 .....e9..... 要求给你a,d两列,如何把文本中对应的a,d两列输入到另一个文本中,变成如下所示? a d a1,d1 a2,d2 a3,d3 a4,d4 a5,d5 a6,d6 a7,d7 a8,d8 a9,d9
第一种方法:先查找并记录要求列在文本中对应的下标,再输出文本对应下标列:
第二种方法:通过正则表达式匹配:
public static void main(String[] args) throws IOException { File fileR = new File("E:\WorkSpace\Test\PatternMatcherReadTest.txt"); File fileW = new File("E:\WorkSpace\Test\PatternMatcherReadTestW.txt"); BufferedReader br = new BufferedReader(new FileReader(fileR)); BufferedWriter bw = new BufferedWriter(new FileWriter(fileW )); try { String s; String[] ss = {"a","d"}; Pattern p =null; while( (s = br.readLine() ) != null){ System.out.println(s); String str=""; for (int i = 0 ; i<ss.length;i++){ p = Pattern.compile(ss[i]+"."); Matcher m = p.matcher(s); if (m.find() ){ str += m.group(0)+","; } } str = str.substring(0, str.length()-1);//末尾去掉符号“,” 保持每一行输出的完整性 bw.write(str); bw.newLine();//换行 bw.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { br.close(); bw.close(); fileR.exists(); fileW.exists(); } }
上一篇:
Java架构师技术进阶路线图
下一篇:
IPV6配置缺省路由与静态路由