0

I'm trying to read a file and set each line from the file as the parameters to the object OS_Process that I made, then place those processes in a linklist queue. However, I keep getting a nullpointerexception. The data file looks as follows. Every new process data is on a new line.

3 //counter
1 3 6 //process 1 data
3 2 6 //process 2 data
4 3 7 //process 3 data

And this is my code

    import java.io.*;
    import java.util.*;

    public class OS_Scheduler
    {
    public static void main(String[] args)
    {
        Queue<OS_Process> jobs = new LinkedList<OS_Process>();

        try
        {
            System.out.print("Enter the file name: ");
            Scanner file = new Scanner(System.in);
            File filename = new File(file.nextLine());

            OS_Process proc = null;
            String s = null;
            int a = 0, p = 0, b = 0;
            BufferedReader input = new BufferedReader(new FileReader(filename));
            StringTokenizer st = new StringTokenizer(s);
            int count = Integer.parseInt(st.nextToken());
            while ((s = input.readLine()) != null)
            {
                st = new StringTokenizer(s);
                a = Integer.parseInt(st.nextToken());
                p = Integer.parseInt(st.nextToken());
                b = Integer.parseInt(st.nextToken());
                proc = new OS_Process(a, p, b, 0);
                jobs.add(proc);
            }
            input.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}

1 Answers1

2

You have a NullpointerException because you've set String s = null; and then you call StringTokenizer stz = new StringTokenizer(s); which is equal to StringTokenizer stz = new StringTokenizer(null); and this gets the Nullpointer.

You don't need to know the count line because the while-loop iterates over all lines in the file and will stop if it reaches the end of the file so update your code as follow:

String s = input.readLine();//read first line to get rid of it
if(s == null){
    //File is empty -> abort
    System.out.println("The file is empty");
    System.exit(0);
}
int a = 0, p = 0, b = 0;
StringTokenizer st;
while ((s = input.readLine()) != null)
{...}

or if you want to use the count you can do it like this:

String s = input.readLine();
checkReadLineNotNull(s);
int a = 0, p = 0, b = 0;
StringTokenizer st = new StringTokenizer(s);
int count = Integer.parseInt(st.nextToken());

for (int i = 0; i < count; i++) {
    s = input.readLine();
    checkReadLineNotNull(s);
    st = new StringTokenizer(s);
    //...
}

//Checks if s != null otherwise kills the programm
private static void checkReadLineNotNull(String s) {
    if(s == null){
        //File is empty abort
        System.out.println("The file is empty");
        System.exit(0);
    }
}
Jérôme
  • 1,254
  • 2
  • 20
  • 25