[Solved] Java program to sort a sequence of numbers in a text file [closed]


Assuming you want help and not complete code:

  1. Read a textfile: FileReader
  2. … line-by-line: BufferedReader and its readLine() method
  3. Integer from text: Integer.parseInt() (assumption: there is one number per line)
  4. Store Integers in something, which orders them, and removes duplicates: TreeSet<Integer>, and its add() method
  5. Get back the numbers (ordered, duplicates removed): iterator() (of the same TreeSet<Integer>)
  6. Writing a textfile: PrintWriter

There are some gaps, but reading the documentation and checking related examples will fill them.


Without any fancy/cryptic construct:

public static void main(String[] args) throws Exception {
    TreeSet<Integer> numbers=new TreeSet<>();
    FileReader fr=new FileReader("numbers.txt");
    BufferedReader br=new BufferedReader(fr);
    String line;
    while((line=br.readLine())!=null){
        numbers.add(Integer.parseInt(line));
    }
    br.close();
    Iterator<Integer> it=numbers.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
    }
    //PrintWriter pw=new PrintWriter("result.txt");
    //while(it.hasNext()){
    //  pw.println(it.next());
    //}
    //pw.close();
}

The commented part would print the result into a file.

Test file: numbers.txt

34
2345
736
2435
7436
2345
2435

11

solved Java program to sort a sequence of numbers in a text file [closed]