2

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??

Jordan Dea-Mattson
  • 5,791
  • 5
  • 38
  • 53

4 Answers4

7

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
Community
  • 1
  • 1
Jordan Dea-Mattson
  • 5,791
  • 5
  • 38
  • 53
0
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++)
           {

           }
    }
}
pNre
  • 5,376
  • 2
  • 22
  • 27
0

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);
live-love
  • 48,840
  • 22
  • 240
  • 204
0
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());
}