Sorting a text file in Java

前端 未结 3 1699
星月不相逢
星月不相逢 2021-01-07 00:25

I have a text file with a list of words which I need to sort in alphabetical order using Java. The words are located on seperate lines.

How would I go about this, R

3条回答
  •  别那么骄傲
    2021-01-07 01:06

    Here is an example using Collections sort:

    public static void sortFile() throws IOException
    {     
        FileReader fileReader = new FileReader("C:\\words.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List lines = new ArrayList();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
    
        Collections.sort(lines, Collator.getInstance());
    
        FileWriter writer = new FileWriter("C:\\wordsnew.txt"); 
        for(String str: lines) {
          writer.write(str + "\r\n");
        }
        writer.close();
    }
    

    You can also use your own collation like this:

    Locale lithuanian = new Locale("lt_LT");
    Collator lithuanianCollator = Collator.getInstance(lithuanian);
    

提交回复
热议问题