不知道这个是不是你要的
public class SortData {
public static void main(String[] args) {
String oldPath = "C:/Users/东海/Desktop/foo.txt";
String newPath = "C:/Users/东海/Desktop/bar.txt";
try {
sortAndWriteData(oldPath, newPath);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void sortAndWriteData(String path, String newPath)
throws IOException {
ArrayList<HashMap<String, String>> list = getData(path);
writeToText(list, newPath);
Collections.sort(list, new Comparator<HashMap<String, String>>() {
@Override
public int compare(HashMap<String, String> o1,
HashMap<String, String> o2) {
if (o1.get("id").compareTo(o2.get("id")) > 0) {
return 1;
}
if (o1.get("id").compareTo(o2.get("id")) < 0) {
return -1;
}
return 0;
}
});
writeToText(list, newPath);
}
private static void writeToText(ArrayList<HashMap<String, String>> list,
String newPath) throws IOException {
File file = new File(newPath);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
StringBuilder stringBuilder = new StringBuilder();
for (HashMap<String, String> hashMap : list) {
String data=stringBuilder.append(hashMap.get("id")+",")
.append(hashMap.get("name")+",").append(hashMap.get("unknown")+",")
.append(hashMap.get("num")).toString();
bufferedWriter.write(data+"\r\n");
bufferedWriter.flush();
stringBuilder.delete(0, stringBuilder.length());
}
bufferedWriter.close();
}
private static ArrayList<HashMap<String, String>> getData(String path)
throws IOException {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
File file = new File(path);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String content = "";
while (content != null) {
content = bufferedReader.readLine();
if (content == null) {
break;
}
String[] dataArray = content.split(",");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", dataArray[0]);
map.put("name", dataArray[1]);
map.put("unknown", dataArray[2]);
map.put("num", dataArray[3]);
list.add(map);
content = "";
}
bufferedReader.close();
return list;
}
}