File Handling in JAVA processing file data JAVA by Ravinder Nath Rajotiya - April 16, 2021April 16, 20210 Share on Facebook Share Send email Mail Print Print Reading integer from file This program explains how we can read numerical data from a file and process it. Remember we need following steps to read from a file: step-1: create File object and connect the file containing data by passing fileName in object as: File file = new File(“outputFile.txt”); Step-2: Test whether the file exists, if it exists step-3: Create object to Scanner class and connect it to the file containing data pointed by File object “file” as shown below: Scanner inputFile = new Scanner(file); Step-4: Check if the line being pointed by nextLine() has the data, this is done asL: while(inputFile.hasNext()) Step-5 read from thefile sum += inputFile.nextInt(); Now see the complete program, of reading integer values from the file and count the number values in file and find their average. package com.example; import javax.print.DocFlavor; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class fileHandling { public static void main(String[] args) throws IOException { int count=0; int sum =0; double average; File file = new File(“outputFile.txt”); if(file.exists()) { Scanner inputFile = new Scanner(file); // checks that the line pointed has the data to be read, if yes then loop proceeds or exits while(inputFile.hasNext()) { // System.out.println(inputFile.nextLine());// reads the data from the line and moves the pointer to next line sum += inputFile.nextInt(); count++; } inputFile.close(); average= sum/(double)count; JOptionPane.showMessageDialog(null, “Sum of all values:” + sum + “\n” + “The number of values”+ count + “\n“+ “the average is :”+ average); } else { JOptionPane.showMessageDialog(null ,“File does not exist”); } } } Share on Facebook Share Send email Mail Print Print