0
  1. 如何根据字母顺序对 .txt 文件中的所有字符串内容进行排序?例如:这是 txt 文件中的内容:

    1. 安娜
    2. 爱丽丝

    排序后:

    1. 爱丽丝
    2. 安娜
  2. 我将如何清除所有内容并只留下空的 txt 文件?
4

3 回答 3

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();
    }
}
于 2013-09-29T09:23:41.443 回答
0

例如

File file = new File("filepathname.txt");
file.delete();
file.creatFile();
于 2013-09-29T09:09:24.670 回答
0


文件 myFile = null;
BufferedReader br = null;
BufferedWriter bw = null;
字符串 [] 名称 = {
“约翰”、“安娜”、“1”、“爱丽丝”、
“艾米”、“乔伊”、“亚历克斯”、“0”};

尝试 {
myFile = new File("unsorted strings.txt");
myFile.createNewFile();
bw = new BufferedWriter(new FileWriter(myFile));

for (int i = 0; i < name.length; i++){
bw.write(name[i]);
bw.newLine();
}

bw.close();
br = new BufferedReader(new FileReader(myFile));
字符串温度 = "";
整数计数器 = 0;

while((temp = br.readLine()) != null){
//temp = temp.trim();

//temp = temp.substring(1,temp.length()).toLowerCase();
//名称[计数器] = fChar + temp;
//计数器++;

名称[计数器] = 温度;
计数器++;
}

br.close();

//java.util.Arrays.sort(name);

java.util.Arrays.sort(name,new java.util.Comparator< String >(){
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 < name.length; i++){
bw.write(name[i]);
bw.newLine();

}


bw.close();


myFile = new File("空文件.txt");
myFile.createNewFile();
bw = new BufferedWriter(new FileWriter(myFile));
bw.write("");
bw.close();

}catch (Exception ex) {
ex.printStackTrace();
}

于 2013-10-04T17:08:15.430 回答