我正在从三个文件中读取数据,然后我想根据某些条件对记录进行排序
每个文件都有以下格式的记录
名字姓氏性别颜色日期
这是我拥有的代码...我只能使用 collections.sort 对名字进行排序...我如何对其他列进行排序...任何帮助将不胜感激..
import java.io.BufferedInputStream;
import java.io.*;
import java.sql.*;
import java.io.RandomAccessFile;
import java.io.*;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.Object;
import java.util.Vector;
import java.util.*;
/**
* This program reads a text file line by line and print to the console.
* It uses FileOutputStream to read the file.
*/
public class test1 {
public static void main(String[] args)
{
try {
ArrayList<String> rows = new ArrayList<String>();
// ArrayList<String> rows1 = new ArrayList<String>();
// ArrayList<String> rows2 = new ArrayList<String>();
// ArrayList<String> rows3 = new ArrayList<String>();
BufferedReader comma = new BufferedReader(new FileReader("C:\\comma.txt"));
BufferedReader pipe = new BufferedReader(new FileReader("C:\\pipe.txt"));
BufferedReader space = new BufferedReader(new FileReader("C:\\space.txt"));
String c= "";
String p;
String s;
while((c = comma.readLine()) != null) {
rows.add(c);
}
Collections.sort(rows);
// Collections.sort(rows2);
FileWriter writer = new FileWriter("output.txt");
for(String cur: rows)
{
writer.write(cur+"");
}
// for(String cur: rows1)
// writer.write(cur+"\n");
// for(String cur: rows2)
// writer.write(cur+"\n");
comma.close();
// pipe.close();
// space.close();
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
您当前正在根据表示整行的字符串进行词法排序。在您的文件格式中,该行以名字开头,因此这就是您用于排序的内容。
如果你想按姓氏排序,你真的没有办法,只能解析每一行,以便程序能够识别姓氏。这将使你的程序变得更加复杂。
您可以使用 StringTokenzier 或正则表达式来标识字符串中的姓氏。 然后您可以使用自定义比较器基于此进行排序。
一种更 OOP 的方法是将每个记录表示为一个对象,然后使用 Collections.sort() 并根据其字段使用自定义比较器。虽然很长,但这是正确的“面向对象方式”。
如果您只是想要一个快速而肮脏的解决方案,您可能需要使用更适合文本操作的语言,例如 Perl 或 Python...
关于java - 按姓氏排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1517745/