user2064844
user2064844

Reputation: 5

why do i get nullpointerexeption?

class DAOBilTextFile implements DAOBil {
private ArrayList<DTOBil> dtoBilar;


public DTOBil dtobil;


public DAOBilTextFile() {
 dtoBilar = new ArrayList<DTOBil>();   
 Charset charset = Charset.forName("UTF-8");
BufferedReader reader = null;


try {
        try{
        reader = Files.newBufferedReader(Paths.get("databilar.txt"), charset);

        String line = null;
        DTOBil bil = null;
         while((line = reader.readLine()) != null){
                 //tar in line och lägger in den i en array med hjälp av ; för att splitta datat
                 String strBilar[] = line.split(";");
                bil = new DTOBil(strBilar[0], strBilar[1], strBilar[2], strBilar[3]);
                //lägger till bil i arraylistan
                dtoBilar.add(bil);
             }reader.close();//this line is the error!

    }finally{
        reader.close();
        }} catch (IOException ioexp) {
        System.out.println(ioexp.getMessage());
    }




}

@Override
public void create(DTOBil dtobil) {
     Charset charset = Charset.forName("UTF-8");
    //klasser för att skriva till textfil
    BufferedWriter writer = null;


        try {
        writer = Files.newBufferedWriter(Paths.get("databilar.txt"), charset, StandardOpenOption.APPEND);
        writer.write(dtobil.getRegnr() + ";"
                    + dtobil.getMarke() + ";"
                    + dtobil.getModell() + ";"
                    + dtobil.getsokVag());
            writer.newLine();
            System.out.println("La till en bil");
            writer.close();
    } catch (IOException ioexp) {
       System.out.println(ioexp.getMessage());
     }
}

I get a "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at swing.labb3.DAOBilTextFile.(DAOBilTextFile.java:50)" but why? i don't understand? and my friend has done the exact same thing and his code works.... This isn't all of the code, but I've placed line 50 in the comments.

Thanks for the help!

Upvotes: 0

Views: 114

Answers (1)

Boann
Boann

Reputation: 50021

Seemingly, you're missing the databilar.txt file, so the newBufferedReader call throws an IOException. So it diverts to the finally block and tries to close the reader, but since the reader was not set by the newBufferedReader call it is still null, and the attempt to close it throws a NullPointerException. In the finally block, you need a test for that:

} finally {
    if (reader != null) reader.close();
}

Then it will be able to harmlessly exit that finally block and get to the IOException catcher in the outer try block.

But the biggest problem is that it can't find the file.

Upvotes: 2

Related Questions