Reading file data into an array in JAVA

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;
public class arrays

public static void main(String[] args) throws IOException


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”);




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)


values[i] = inputFile.nextInt();




// Display data read into the array

for (int data : values)






error: Content is protected !!