Reading file data into an array in JAVA JAVA by Ravinder Nath Rajotiya - April 18, 20210 Share on Facebook Share Send email Mail Print Print Table of Contents Toggle Reading Numeric data from file into an arrayExample reading from a file into an array Reading Numeric data from file into an array In this post we look out how we can integer read data from a file into an array. For this we need the following steps. Step-1: Create an array to store data read from file Step-2: create file object of class file and connect to file Step-3: Check if the file exist Step-4: Create object of Scanner class and make connection to input file using file object Step-5: Check if the current line has data in it using hasNext() Step-6: read from the line and set the pointer to begining of next line using object.nextLine() Step-7: close file when done Step-8: Display / process data read from the file Example reading from a file into an array package com.example; import java.io.IOException; public class arrays { public static void main(String[] args) throws IOException { //Step-1 int []values = new int[10]; //create array of 10 elements int i=0; //index for loop //Step-2 Create file object and make connection to file File file= new File(“dataFile.txt”); //Step-3 if(file.exists()) { //Step-4: Scanner inputFile = new Scanner(file); //Step-5 Read from file untill end of file or end of array reached while(inputFile.hasNext() && i <values.length) { //Step-6: values[i] = inputFile.nextInt(); i++; } //Step-7 inputFile.close(); // Display data read into the array for (int data : values) { System.out.println(data); } } } } Share on Facebook Share Send email Mail Print Print