I am writing some Java code to read each line of a data file into an array list, shuffle that list, and then perform some further operations on the shuffled data. The problem is that, after shuffling, I am getting null elements for some of the elements in the array list.
//this file contains the data
String input = ...;
//this file contains the number of rows in the data file
String input2 = ...;
FileInputStream fstream2 = new FileInputStream(input2);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader brIndex = new BufferedReader(new InputStreamReader(in2));
for(int i = 1; i <= N; i++) {
FileInputStream fstream = new FileInputStream(input+(i+1)+".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader brData = new BufferedReader(new InputStreamReader(in));
num = Integer.parseInt(brIndex.readLine());
ArrayList<String> temp = new ArrayList<String>();
for(int j = 0; j < num; j++) {
temp.add(brData.readLine());
}
brData.close();
Collections.shuffle(temp);
//read in shuffled data
for(int j = 0; j < num; j++) {
rowData = temp.get(j); ...
}
In executing the code, I get a NullPointerException after this when working with rowData. The original file has 17,169 rows (none of them are null). temp.size() is also 17,169 but when I printed temp out to the console, temp.get(j) was null for some j and not for others.
Can anyone explain to me why this is the case and how to avoid it?
The problem might be there are not enough lines in the file as
num.Try:
You could also check for null elements in the list before you actually shuffle the list, as shuffle does not insert any new element to the list.