Read integers from a file, sort, and print.

BestJewSinceJC

Since I keep seeing people asking how to read the Integers from a File, I figured this simple snippet might be useful. What it does is it creates a new Scanner Object based on the File Object "test.txt" then it reads all of the Integers from that file, skipping over anything else that was found in the file, and adding the Integers to an ArrayList. It then sorts the ArrayList and prints out the sorted numbers. The file must exist otherwise this example will crash.

4,120 Views
About the Author
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;


public class IntegersFromFile {

	public static void main(String[] args) {
		Scanner file = null;
		ArrayList<Integer> list = new ArrayList<Integer>();
		
		try {
			file = new Scanner(new File("test.txt"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		while(file.hasNext()){
			if (file.hasNextInt()) list.add(file.nextInt());
			else file.next();
		}
		
		Collections.sort(list);
		
		for (Integer i: list) System.out.println(i);
		
	}

}
kvass 70 Junior Poster

Out of curiosity, what sorting algorithm does the Collections class' sort method use?

BestJewSinceJC 700 Posting Maven
jade_91 0 Light Poster

ok well i tried this but i want to modify it to sort text rather than numbers not sure how to do it I tried this

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner; 

 public class NameSort { 	

public static void main(String[] args) {	
	Scanner file = null;		
[ArrayList<String> list = new ArrayList<String>();]

 		try {	
		file = new Scanner(new File("names.txt"));
		} catch (FileNotFoundException e) {	
		e.printStackTrace();		} 	

	while(file.hasNext()){			
if (file.hasNextString()) list.add(file.nextString());
			else file.next();		}

 		Collections.sort(list); 		


for (String s: list) System.out.println(s); 	
	} 

}

but it doesnt want to work keeps coming back with errors any help would be much appreciated

devninja 2 Light Poster

why do you have brackets around the arraylist decleration?

tn464 0 Newbie Poster

if i were to want to get the total of the number in a files where would i insert the code

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

The read loop starts on line 20:
while(file.hasNext()){
That loop is where you'd perform any operations you want to do with each entry.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.