/* * This program shows how to read in a file of unknown size into an array, * then resize the array to exactly fit the data. * */ import java.io.*; import java.util.*; public class Test { public static void main(String[] args) throws FileNotFoundException { int[] x = new int[100]; // This must be larger than anticipated data amount Scanner inFile = new Scanner(new File("input.txt")); int size = readData(inFile, x); System.out.println("Size = " + size); System.out.println("X = " + Arrays.toString(x)); x = resize(x, size); System.out.println("\nAfter resizing:"); System.out.println("X = " + Arrays.toString(x)); } //--------------------------------------------------- // This method reads data into an array from the specified // file, returning the number of elements read. public static int readData(Scanner inFile, int[] a) { int count = 0; while (inFile.hasNextInt()) { a[count] = inFile.nextInt(); count++; } return count; } //---------------------------------------------------- // This method resizes an array. public static int[] resize(int[] a, int newSize) { int[] temp = new int[newSize]; for (int i = 0; i < newSize; i++) { temp[i] = a[i]; } return temp; } }