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.
Read integers from a file, sort, and print.
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
BestJewSinceJC 700 Posting Maven
jade_91 0 Light Poster
devninja 2 Light Poster
tn464 0 Newbie Poster
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.