要使用Java对文本文件中的记录进行排序,您可以遵循以下步骤:
BufferedReader
类从文件中读取所有行,并将其存储在一个List<String>
中。import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public List<String> readLines(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines;
}
Collections.sort()
方法对List<String>
进行排序。import java.util.Collections;
import java.util.List;
public void sortLines(List<String> lines) {
Collections.sort(lines);
}
BufferedWriter
类将排序后的列表写回文件。import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public void writeLines(String filePath, List<String> lines) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedWriter.close();
}
public static void main(String[] args) {
String filePath = "input.txt";
String outputFilePath = "output.txt";
try {
List<String> lines = readLines(filePath);
sortLines(lines);
writeLines(outputFilePath, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
这样,您就可以使用Java对文本文件中的记录进行排序了。
领取专属 10元无门槛券
手把手带您无忧上云