jayeshcp
1/7/2015 - 3:37 PM

Reading integers from data file

Reading integers from data file

7
10
20
30
40
50
60
70

data.txt file contains data in following format:

First line contains a number N and N data inputs follow in separate lines. This format is popular in programming contests.

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class FileRead {
  public static void main(String[] args) {
    BufferedReader bf = null;
    
    try {
      bf = new BufferedReader(new FileReader(new File("data.txt")));
      int N = 0;

      String s = bf.readLine();
      N = Integer.parseInt(s);  // Number of inputs to read
      int[] numbers = new int[N];
      for(int i = 0; i < N; i++) {
        numbers[i] = Integer.parseInt(bf.readLine());
      }
      
      // Display data values
      for(int number : numbers) {
        System.out.println(number);
      }
    } catch( IOException ioe) {
      System.out.println("Exception reading file: " + ioe.toString());
    } catch(NumberFormatException npe) {
      System.out.println("Incorrect data format: " + npe.toString());
    }finally {
      try {
        if(bf != null)
          bf.close();
      } catch(IOException ioe) {
        
      }
    }
  }
}