如何根据字母顺序对.txt文件中的所有字符串内容进行排序?例如 : 这是txt文件中的内容:
排序后:
答案 0 :(得分:1)
public static void main(String[] args){
try {
File file = new File("input.txt")
List<String> allLines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
Collections.sort(allLines);
//For deleting
file.delete();
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 1 :(得分:0)
例如
File file = new File("filepathname.txt");
file.delete();
file.creatFile();
答案 2 :(得分:0)
文件myFile = null;
BufferedReader br = null;
BufferedWriter bw = null;
String [] name = {
“约翰”,“AnNa”,“1”,“AliCe”,
“Ammy”,“JOey”,“Alex”,“0”};
试试{
myFile = new File(“unsorted strings.txt”);
myFile.createNewFile();
bw = new BufferedWriter(new FileWriter(myFile));
for(int i = 0; i&lt; name.length; i ++){
bw.write(名称[I]);
bw.newLine();
}
bw.close();
br = new BufferedReader(new FileReader(myFile));
String temp =“”;
int counter = 0;
while((temp = br.readLine())!= null){
// temp = temp.trim();
// char fChar = temp.toUpperCase()。charAt(0);
// temp = temp.substring(1,temp.length())。toLowerCase();
// name [counter] = fChar + temp;
//计数器++;
名称[counter] = temp;
计数器++;
}
br.close();
//java.util.Arrays.sort(name);
java.util.Arrays.sort(name,new java.util.Comparator&lt; String&gt;(){
public int compare(String o1,String o2){
return o1.trim()。toLowerCase()。compareTo(o2.trim()。toLowerCase());
}});
myFile = new File(“sorted strings.txt”);
myFile.createNewFile();
bw = new BufferedWriter(new FileWriter(myFile));
for(int i = 0; i&lt; name.length; i ++){
bw.write(名称[I]);
bw.newLine();
}
bw.close();
myFile = new File(“empty file.txt”);
myFile.createNewFile();
bw = new BufferedWriter(new FileWriter(myFile));
bw.write( “”);
bw.close();
} catch(Exception ex){
ex.printStackTrace();
}