【发布时间】:2025-11-21 21:10:02
【问题描述】:
我目前正在读取和写入文本文件,但我想不出一种排序方式。我以为我可以按模式排序。我想按模式(0-9,A-Z,a-z)对 java 字符串数组进行排序。基本上我想忽略非字母数字字符,用字母前面的数字和小写字母前面的大写字母(即 0-9、A-Z、a-z)进行排序。我想删除只有非字母数字字符的行。
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
// SORT GOES HERE
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
【问题讨论】:
-
为什么在读完所有行之后不对它们进行排序?您可以使用
Collections.sort(List l, Comparator c)来执行此操作... (docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/…)