要用Java写个东西读取txt中的数据,若id1或者id2的值不同,就插入END,START(详细见结果),最后只输出修改后的id3列。我对java不熟,读入txt和写出新txt还是能自己弄的,但是不会比较id1的值或者id2的值,请大家帮忙,最好带注释,谢谢 :oops: 源文件:id1 id2 id3100037 1 Q 100037 1 SR 100037 1 Q 100037 1 SR 100039 1 Q 100039 1 SR 100044 1 Q 100044 1 SR 100048 1 Q 100048 1 Q 100048 1 SR 100048 2 Q 100048 2 Q 100048 2 SR 100078 1 Q 100078 1 SH 100078 1 SR 100078 1 Q希望得到的结果:STARTQ SR Q SR ENDSTARTQ SR ENDSTARTQ SR ENDSTARTQ Q SR ENDSTARTQ Q SR ENDSTARTQ SH SR Q END
3 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
public static void main(String[] args) throws Exception{ String inFile = "D:\in.txt"; String outFile = "D:\out.txt"; BufferedReader bs = null; BufferedWriter bw = null; try{ bs = new BufferedReader(new FileReader(new File(inFile))); List outData = new ArrayList(); String line = null; String[] data = null; //如果确定ID1一直是整数的活,可以用整数比,否则可以用字符串的equals比较 int oldId1 = 0; int newId1 = 0; int oldId2 = -1; int newId2 = -1; while((line = bs.readLine()) != null){ data = line.split(" "); newId1 = Integer.parseInt(data[0]); newId2 = Integer.parseInt(data[1]); if((oldId1 != newId1) || (oldId2 != newId2)){ if(!outData.isEmpty()){ outData.add("END"); } outData.add("START"); } oldId1 = newId1; oldId2 = newId2; outData.add(data[2]); } if(!outData.isEmpty()){ outData.add("END"); bw = new BufferedWriter(new FileWriter(new File(outFile))); for(String s : outData){ bw.write(s + "\r\n"); } } }catch(Exception e){ e.printStackTrace(); }finally{ if(bs != null){ bs.close(); } if(bw != null){ bw.close(); } } }
写了一个main方法,你自己改成带参数的方法吧!~~~ :D 随便写的没多想,别闲不好。
添加回答
举报
0/150
提交
取消