How do I sort records in a text file using Java?
Here's something I came up with:
import java.io.*;
import java.util.*;
public class Sort {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("fileToRead"));
Map<String, String> map=new TreeMap<String, String>();
String line="";
while((line=reader.readLine())!=null){
map.put(getField(line),line);
}
reader.close();
FileWriter writer = new FileWriter("fileToWrite");
for(String val : map.values()){
writer.write(val);
writer.write('\n');
}
writer.close();
}
private static String getField(String line) {
return line.split(" ")[0];//extract value you want to sort on
}
}
package com.myFiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
public class FilesReaderWriter {
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
PrintWriter outputStream = null;
ArrayList<String> rows = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader("Input.txt"));
outputStream = new PrintWriter(new FileWriter("Output.txt"));
String file;
while ((file = reader .readLine()) != null) {
rows.add(file);
}
Collections.sort(rows);
String[] strArr= rows.toArray(new String[0]);
for (String cur : strArr)
outputStream.println(cur);
} finally {
if (reader != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
Here's a pretty lazy way of doing it since you are only sorting first word:
ArrayList<String> rows = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String s;
while((s = reader.readLine())!=null)
rows.add(s);
Collections.sort(rows);
FileWriter writer = new FileWriter("output.txt");
for(String cur: rows)
writer.write(cur+"\n");
reader.close();
writer.close();
Using sort
:
aaron@ares ~$ sort data.txt
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
aaron@ares ~$ sort data.txt > sorted.txt
aaron@ares ~$ cat sorted.txt
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
... or using python
:
aaron@ares ~$ python -c "import sys; print ''.join(sorted(sys.stdin))" < data.txt > sorted.txt
aaron@ares ~$ cat sorted.txt
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins