Sort content in a txt file

If you have a file with come words or terms on each line, you may want to sort it. Java Arrays.sort is common nice function to do this. Collections.sort() is another nice say. Here is an example and code.
E.G. in a file, you have the following txt.

dog 
cat
--windows
--kankan
pps
game
--annot be guaranteed 
as it is, generally speaking, 
--impossible to make any hard gu
arantees in the p
--resence of unsynchr

Here is the code to sort the lines, excluding lines starting with “-“.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
 
 
public class SortFileContent {
	public static void sortObserve() throws IOException {
		File fin = new File("c:\\input.txt");
		File fout = new File("c:\\sorted.txt");
 
 
		FileInputStream fis = new FileInputStream(fin);
		FileOutputStream fos = new FileOutputStream(fout);
 
		BufferedReader in = new BufferedReader(new InputStreamReader(fis));
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
 
		String aLine;
		ArrayList<String> al = new ArrayList<String> ();
 
 
		int i = 0;
		while ((aLine = in.readLine()) != null) {
			//get the lines you want, here I don't want something starting with - or empty
			if (!aLine.trim().startsWith("-") && aLine.trim().length() > 0) {
				al.add(aLine);
				i++;
			}
		}
 
		Collections.sort(al);
		//output sorted content to a file
		for (String s : al) {
		    System.out.println(s);
		    out.write(s);
			out.newLine();
			out.write("-----------------------------------------");
			out.newLine();
		}
 
		in.close();
		out.close();
	}
}

Finally you get the following in sorted.txt file.

arantees in the p
-----------------------------------------
as it is, generally speaking, 
-----------------------------------------
cat
-----------------------------------------
dog 
-----------------------------------------
game
-----------------------------------------
pps
-----------------------------------------

Leave a Comment