I have a question about handling binary files. I am trying to create a method called read in a user defined class called Record that will handle the data from the file.
Each record has 84bytes and the first 20bytes is a String, and the rest, 64bytes is for 16 int values. My code so far looks like this:
import java.io.*;
class Record
{
private String country;
private int[] popData = new int[16];
public void read(DataInputStream is) throws IOException
{
byte[] temp = new byte[21];
for (int i = 0; i < 20; i++)
{
temp[i]= is.readByte();
if (temp[i] == '\0')
temp[i] = ' ';
}
String convert = new String(temp);
country = convert;
for (int i = 0; i < 16; i++)
popData[i] = is.readInt();
}
public String getName()
{
return country;
}
public int getPopulation(int y)
{
int dat = 0;
if (y < 1986 || y > 2001)
dat = 0;
else
{
if (y == 1986)
dat = 0;
else if (y == 1987)
dat = 1;
else if (y == 1988)
dat = 2;
else if (y == 1989)
dat = 3;
else if (y == 1990)
dat = 4;
else if (y == 1991)
dat = 5;
else if (y == 1992)
dat = 6;
else if (y == 1993)
dat = 7;
else if (y == 1994)
dat = 8;
else if (y == 1995)
dat = 9;
else if (y == 1996)
dat = 10;
else if (y == 1997)
dat = 11;
else if (y == 1998)
dat = 12;
else if (y == 1999)
dat = 13;
else if (y == 2000)
dat = 14;
else if (y == 2001)
dat = 15;
}
return popData[dat];
}
}
public class Asst02
{
public static void main(String[] args) throws IOException
{
long numRec;
numRec = (new File("popdata.bin")).length() / 84;
Record[] rec = new Record[(int)numRec];
DataInputStream in = new DataInputStream(new FileInputStream("popdata.bin"));
for (int i = 1; i < numRec; i++)
{
rec[i].read(in);
}
System.out.println(rec[1]);
}
}
When I run the program it gives me a NullPointerException in main at the for loop. What am I doing wrong?