本帖最后由 fanalin000 于 2012-07-23 10:36:17 编辑 要用Java写个东西读取txt中的数据,若id1或者id2的值不同,就插入END,START(详细见结果),最后只输出修改后的id3列。我对java不熟,读入txt和写出新txt还是能自己弄的,但是不会比较id1的值或者id2的值,请大家帮忙,最好带注释,谢谢
源文件:
id1 id2 id3
100037 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
希望得到的结果:
START
Q
SR
Q
SR
END
START
Q
SR
END
START
Q
SR
END
START
Q
Q
SR
END
START
Q
Q
SR
END
START
Q
SH
SR
Q
END
------最佳解决方案--------------------
package com.li;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(new File("e:/1.txt"))));
String temp = "";
Set<Text> texts = new TreeSet<Text>();
while((temp=buf.readLine())!=null){
Text text= new Text(temp);
texts.add(text);
}
for (Text text : texts) {
System.out.println("START\n"+text.getContent()+"\nEND");
}
}
}
class Text implements Comparable<Text>{
private String content =null;
private String header = null;
public Text(String content){
setContent(content);
this.header = content.split(" ")[0];
this.content = content.split(" ")[2];
}
@Override
public int compareTo(Text o) {
if(header.equals(o.getHeader())){
o.setContent(o.getContent()+"\n"+content);
return 0;
}else return 1;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
}
------其他解决方案--------------------
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("d:\\from.txt");
BufferedReader br = new BufferedReader(fr);
StringBuffer buf = new StringBuffer();