Suppose we have a data file containing two columns of tab-delimited integers as follows:
2 3 4 6 6 9 ...
The following example fetches data from this file and store it in an ArrayList so that it can be used for whatever purpose.
import java.io.*;
import java.util.*;
public class ReadFromFile
{
public static void main(String[] args) {
String filename = "";
String line = "";
ArrayList<Integer> al = new ArrayList<Integer>();
ArrayList<Integer> bl = new ArrayList<Integer>();
// get filename from user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("filename: ");
try {
filename = br.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
// open and read file
try {
FileInputStream fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader brfile = new BufferedReader(new InputStreamReader(in));
while ((line = brfile.readLine()) != null) {
String[] numbers = line.split("\\t");
al.add(Integer.valueOf(numbers[0]));
bl.add(Integer.valueOf(numbers[1]));
}
in.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
System.out.println(al.toString());
System.out.println(bl.toString());
}
}
output
filename:
Book1.txt
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
The first part prompts the reader to type the filename. System.in takes user input. Then the program opens the specified file and reads it line by line in the while loop. line.split(â\\tâ) splits each line on tabs and its output is a String where each splitted item is an array element. Integer.valueOf() casts each of these elements to an Integer objects. The Integers are added to respective ArrayLists al and bl on the same lines respectively. Last two prints, print the contents of the ArrayList to screen.