Question:
I have a file that has two columns of integers that need to be read in and populated into two separate ArrayLists with its content.
Code:
import java.io.*; import java.util.*; public class FileIntoArray { public static void main(String[] args) { ArrayList<Integer> col1 = new ArrayList<>(); ArrayList<Integer> col2 = new ArrayList<>(); try { FileInputStream is = new FileInputStream("data.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str; String values[]; while ((str = br.readLine()) != null) { values = str.split(" "); col1.add(Integer.parseInt(values[0])); col2.add(Integer.parseInt(values[1])); } } catch (Exception e) { // needs better exception handling in real world System.out.println(e.toString()); col1.clear(); col2.clear(); } System.out.println("col1: " + col1); System.out.println("col2: " + col2); } }
Output:
$ java FileIntoArray col1: [115, 123, 116, 113, 112, 104, 110, 218, 208] col2: [257, 253, 246, 243, 239, 239, 238, 243, 242] $ cat data.txt 115 257 123 253 116 246 113 243 112 239 104 239 110 238 218 243 208 242