Java:如何清除和排序.txt文件中的所有内容?

时间:2013-09-29 09:02:20

标签: java sorting clear

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

    1. JHON
    2. 安娜
    3. 爱丽丝
    4. 排序后:

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

3 个答案:

答案 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();
}