I've been trying to create a Java program to read a file "100.txt" that contains 100 integers and then store them into an int array. Later, I'm going to have it print the array and sort the numbers in the array, but I want to get it to read the text file and store the numbers in the array and convert it to an int array first. How do I do that?
I've tried a few different things. I know how to read a text file from a Scanner and create an array, but I've never changed the type (in this case, String to int). If any of you could help and give me some pointers on how to go about this, that would be much appreciated.
try { File file = new File("100.txt"); Scanner input = new Scanner(file); while (input.hasNextLine()) { String line = input.nextLine(); System.out.println(line); } input.close(); } catch (Exception ex) { ex.printStackTrace(); } int[] array = new int[file.length]; int i, n = array.length; for (i = 0; i < n; i++) { array[i] = Integer.parseInt(file[i]); } }