views:

174

answers:

5

hi, I'm getting java.lang.NullPointerException at while ((len = in.read(buf , 0 , buf.length)) >= 0) in following method:

public void copy(String  src, File dst) throws IOException {

  InputStream in = getClass().getResourceAsStream(src); 
        OutputStream out = new FileOutputStream(dst);

        byte[] buf = new byte[1012];
        int len;
        while ((len = in.read(buf , 0 , buf.length)) >= 0) {
            out.write(buf, 0, len);
            buf = null;
        }
        in.close();
        out.close();
    }

I'm not getting the coz.I will be thankful if I get the solution.thanks in advance.......

+10  A: 

You set

buf = null;

at the first iteration, at the second buf.length throws the NullPointerException.

Alberto Zaccagni
+2  A: 

Because you set buf = null; after the first iteration of the loop. It will fail on the second run of the while-loop.

Kosi2801
A: 

You need to something like below inside the loop:

buf = new byte[1012];

Or you could remove the buf = null entirely.

fastcodejava
A removal of buf=null will be sufficient
Hardcoded
+1  A: 

buf = null; inside your while loop is causing the problem, try commenting that line.

Rakesh Juyal
+2  A: 

I see two possible NullPointer here:

  1. The buf=null;, which definitly causes a NullPointerException on the second iteration.
  2. getResourceAsStream will return null if src wasn't found.
Hardcoded