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, Read them into an array list and then sort that??
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, Read them into an array list and then sort that??
 
    
    This is a simple four step process, with three of the four steps addressed by Stackoverflow Questions:
 
    
     
    
    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++)
           {
           }
    }
}
 
    
    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);
 
    
    public List<String> readFile(String filePath) throws FileNotFoundException {
    List<String> txtLines = new ArrayList<>();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while (!((line = reader.readLine()) == null)) {
            txtLines.add(line);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return txtLines.stream().sorted().collect(Collectors.toList());
}
