0

I am learning Java. I have some code where I tried to call file names on directory and make it models to show table on main

Code :

import java.io.File;
import java.util.StringTokenizer;
import javax.swing.table.*;

public class SheetList {    directory
    public static DefaultTableModel load(){
        File file = new File("sheet.");
        File list[] = file.listFiles(); //load file list
        String col[] = new String[2];
        String colNames[] = {"Title", "Artist"};
        DefaultTableModel model = new DefaultTableModel(colNames, 0);
        for(int cnt = 0; cnt < list.length; cnt++){  // ERROR
            String name = list[cnt].getName();            
            if(list[cnt].isFile()){     
                StringTokenizer stok = new StringTokenizer(name, " - ");
                String token = stok.nextToken();          
                col[0] = token;         
                token = stok.nextToken();
                col[1] = token;         
                model.addRow(col);  
            }
        }
        return model;
    }
}

but a problem occurs on the marked line

Thread [main] (Suspended (exception NullPointerException))  
SheetList.load() line: 12   
Main.main(String[]) line: 14    
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136

1 Answers1

1

listFiles() may return null and you're not guarding against it. Accessing the length property will cause a NPE if the object is null.

Before your loop check if the file array is null and you'll be fine.

Reference: http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles()

Another thing to keep in mind is that you should check that the File you've created exists and that it is a directory.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists()

http://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()

John Scattergood
  • 1,032
  • 8
  • 15
  • thx for answer :) there was no path like ("sheet.*) and your reference about exists() seems useful. thankyou –  Dec 14 '15 at 03:40