Hi I am having trouble reading a file inside constructor from a method. Here is my code:-
I can compile my code but I am getting runtime errors.
Error

Exception in thread "main" java.lang.NullPointerException
	at java.io.FileInputStream.<init>(FileInputStream.java:133)
	at java.io.FileInputStream.<init>(FileInputStream.java:96)
	at java.io.FileReader.<init>(FileReader.java:58)
	at Testwow.readFile(Testwow.java:25)
	at Testwow.<init>(Testwow.java:13)
	at Testwow.main(Testwow.java:45)

fh = new BufferedReader(new FileReader(filename)); line 25
readFile(filename); line 13
Testwow wow = new Testwow(); line 45
Can somebody help please ?

import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.*;

public class Testwow {
    public String filename;
    public int one;
    public int two;
    public String f[];
   
   
    public Testwow(){
        readFile(filename);
        System.out.println(filename);
       
    }
   
    public void readFile(String filename){
           this.filename = filename;
           System.out.println(filename);

           String n = null;  
           BufferedReader fh;
        try{
            fh = new BufferedReader(new FileReader(filename));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){

                f = n.split("\t");
                one = Integer.parseInt(f[0].trim());
                two = Integer.parseInt(f[1].trim());

                System.out.println(one);
                System.out.println(two);
 
            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
       }
   
    public static void main(String args[]){
        Testwow wow = new Testwow();
        wow.readFile(args[0]);
    }

}

Thanks

You forget to assign filename.

public String filename="file.txt";

or Remove readFile(filename)

public Testwow(){
      //  readFile(filename);
     //   System.out.println(filename);
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.