Sorting a text file in Java

前端 未结 3 1700
星月不相逢
星月不相逢 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 00:49
    import java.io.*;
    import java.util.*;
    
    public class example
    {
        TreeSet<String> tree=new TreeSet<String>();
        public static void main(String args[])
        {
            new example().go();
        }
        public void go()
    
        {
            getlist();
            System.out.println(tree);
    
        }
         void getlist()
        {
            try
            {
                File myfile= new File("C:/Users/Rajat/Desktop/me.txt");
                BufferedReader reader=new BufferedReader(new FileReader(myfile));
                String line=null;
                while((line=reader.readLine())!=null){
                    addnames(line);
    
    
                }
            reader.close();
            }
    
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
    
        }
        void addnames(String a)
        {
               tree.add(a);
               for(int i=1;i<=a.length();i++)
               {
    
               }
        }
    }
    
    0 讨论(0)
  • 2021-01-07 00:50

    This is a simple four step process, with three of the four steps addressed by Stackoverflow Questions:

    1. Read each line and turn them into Java String
    2. Store each Java String in a Array (don't think you need a reference for this one.)
    3. Sort your Array
    4. Write out each Java String in your array
    0 讨论(0)
  • 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<String> lines = new ArrayList<String>();
        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);
    
    0 讨论(0)
提交回复
热议问题