java 中如何读入txt文本中的多种数据并将其写入到一个新的txt文档中

2025-01-08 12:45:46
推荐回答(1个)
回答1:

package test.removedata;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.Iterator;
public class RemoveData{
public static void main(String[] args){
TreeSet set = new TreeSet();
BufferedReader reader = null;
BufferedWriter writer = null;
String aData = null;
try{
//in the datas
reader= new BufferedReader(new FileReader(new File("1.txt")));
while((aData = reader.readLine()) != null){
MyData tempData = createData(aData);
if(tempData != null){
set.add(createData(aData));
}

}

Iterator iter = set.iterator();

//out the datas
writer = new BufferedWriter(new FileWriter(new File("2.txt")));

while(iter.hasNext()){
MyData iterData = (MyData)iter.next();
writer.write(iterData.getName() + " " + iterData.getId());
writer.newLine();
}
writer.flush();
}catch(IOException ex){
ex.printStackTrace();
System.err.println("数据文件不存在!");
}finally{
try{
reader.close();
writer.close();
}catch(IOException ex){
ex.printStackTrace();
}

}
}
public static MyData createData(String str){
if(str.trim().length() == 0 || str.trim().equals("")){
return null;
}
String[] temp = str.trim().split("\\s");
int id = 0;
String idStr = str.substring(temp[0].length(),str.length()).trim();
try{
id = Integer.parseInt(idStr);
}catch(NumberFormatException ex){
ex.printStackTrace();
System.err.println("数据格式错误!");
}
return new MyData(id, temp[0]);
}
}

class MyData implements Comparable{
private String name;
private int id;
public MyData(int id, String name){
this.id = id;
this.name = name;
}

public String getName(){
return name;
}
public int getId(){
return id;
}

public int compareTo(MyData data1){
return this.getId() - data1.getId();
}
}