Searching...
Tuesday, July 15, 2014

Sort the contents in txt file

July 15, 2014


A text file can be read line-by-line with a BufferedReader. To sort these lines, we can read them into a List and run a Collections.sort() on the List.
The AlphabeticallySortLinesOfTextInFile class demonstrates this. It reads in a text file line-by-line and adds each line to an ArrayList. When this is done, it sorts the list with Collections.sort(). To display the results, it outputs all the lines to an output file using a PrintWriter and FileWriter.

input.txt
january
february
march
april
may
june
july
auguest
september
october
november
december

SortTheContentsInTxtFile.java

package java9r.blogspot.com;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortTheContentsInTxtFile {
public static void main(String[] args) {
File fin = new File("F:\\input.txt");
File fout = new File("F:\\output.txt");

try {
FileInputStream fis = new FileInputStream(fin);
FileOutputStream fos = new FileOutputStream(fout);

BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

String line = "";
List list = new ArrayList();

while ((line = br.readLine()) != null) {
list.add(line);

}
Collections.sort(list);
for (String temp : list) {
System.out.println(temp);
bw.write(temp);
bw.newLine();
}
br.close();
bw.close();
}

catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();

}

}
}



Output 

0 comments:

Post a Comment

ads2