Skip to content

Instantly share code, notes, and snippets.

@jayeshcp
Created January 7, 2015 15:37
Show Gist options
  • Save jayeshcp/b721bade4d093ccae00d to your computer and use it in GitHub Desktop.
Save jayeshcp/b721bade4d093ccae00d to your computer and use it in GitHub Desktop.
Reading integers from data file

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.

7
10
20
30
40
50
60
70
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) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment