package com.tunji.coursera;

/*This program collects integers and sorts them in either ascending or
descending order as picked in the options given.
There is a need for an enhancement for the program to pick the arrays from
a text file. */

import java.io.*;
import java.util.*;

public class PickSortMerge {

public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(“C:\\Utilities\\Textpad programs\\com\\tunji\\coursera\\numbers.txt”));
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(“C:\\Utilities\\Textpad programs\\com\\tunji\\coursera\\pro.txt”);
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
}
}

Advertisements

13 thoughts on “Java program to read and sort figures from a text file

  1. ok , i have a text file like this ;

    name,surname,age,weight,height

    these are seperated by comma, so i want to list these line by line and sort them by weight. your codes are listing. but when i write same values for exm.

    kaan,asd,25,80,187
    adetunji,zxc,28,80,192 it will take only second one on sorting. am i clear :S sory for my bad english 😦

    Like

  2. 1,asd,asd,sd,asd
    100,sdfsd,fsd,sdf,sdf
    12,dfgd,df,dfg,dfg12
    123,asd,asd,gdfg,fghf
    12,dfsdfsd,fsd,sdf,sdf
    123,asda,sdas,asd,asd
    142,asd,asd,gdfg,fghf
    123,asd,asd,gdfg,fghf
    12,asd,asd,gdfg,fghf

    these are my values. i want to order them by first value. but when i run your code it saved like;

    1,asd,asd,sd,asd
    100,sdfsd,fsd,sdf,sdf
    123,asd,asd,gdfg,fghf
    142,asd,asd,gdfg,fghf
    12,asd,asd,gdfg,fghf

    like this. not taking duplicated..

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s