how to read integer from text file in java

http‮.www//:s‬lautturi.com
how to read integer from text file in java

input.txt

1 2 3
4 15 
6 7
8

java program

/**
 * @author lautturi.com 
 * Java example: Java read list of integer from text file
 */

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

public class Lautturi {
	public static void main(String[] args) throws IOException {
		File file = new File("input.txt");
		long filesize = Files.size(file.toPath());
		Scanner scanner = new Scanner(file);
		
		if (filesize > 0) {
			int[] arr = new int[(int) filesize];
			int i = 0;
			while (scanner.hasNextInt()) {
				arr[i++] = scanner.nextInt();
			}
			System.out.println(Arrays.toString(arr));
		}
	}
}

output:

[1, 2, 3, 4, 15, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Created Time:2017-09-28 14:41:19  Author:lautturi