Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
3
Indexable
Never
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) {

        // Create Object of Scanner class named file and assign null to file
        Scanner file = null;

        // Create a ArrayList to store numbers from test.txt
        ArrayList<Integer> list = new ArrayList<Integer>();

        // try - catch block
        try {
            // opening test.txt file in read mode
            file = new Scanner(new File("test.txt"));
        }
        // if test.txt not found then this will throw an error
        catch (FileNotFoundException e) {
            // display error
            e.printStackTrace();
        }

        // if file found, then while loop to read into file until end of file
        while (file.hasNext()) {
            // reading integers and adding integers to arraylist named list
            if (file.hasNextInt()) list.add(file.nextInt());
            // otherwise, move to next
            else file.next();
        }

        // Now sorting arraylist
        Collections.sort(list);
        // display sorted array list on console
        for (Integer i : list) System.out.print(i + " ");
    }
}