-1

Inside the for loop, depending on if condition, files need to be created every time. While executing the code, NullPointerException pops up.

    File[] tempDir=null; 
    for(  )
    {
    if(condition){
        try {
            tempDir[l]=new File(tempFileName);
            if(l==0){
                tempDir[l++].mkdir();
                /*code*/
            }
            if (!tempDir[l].exists()){
                tempDir[l++].mkdir();
                /*code*/
            }
        }
    }
Eran
  • 387,369
  • 54
  • 702
  • 768
Gokul S
  • 23
  • 6

2 Answers2

2

You don't initialize the tempDir array.

Change

File[] tempDir=null; 

to

File[] tempDir=new File[somePositiveInteger]; 

tempDir[l] would throw a NullPointerException if tempDir is null.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • public static void copyFileContents(File source, File dest)throws IOException{ .... } try { tempDir[l]=new File(tempFileName); if(l==0){ tempDir[l++].mkdir(); copyFileContents(new File("D:\\gokul\\Auto"+"\\"+fileName+".txt"),new File("D:\\gokul\\Dest"+"\\"+tempFileName+"\\"+fileName+".txt")); } /*Showing Null Pointer Exception*/ – Gokul S Nov 05 '14 at 06:44
0

You are initializing your File array to null here ,

File[] tempDir=null;

So you are getting NPE when you are trying to find the first element of the File Array here ,

tempDir[l]=new File(tempFileName); // tempDir[l] represents the element at position 1

So you should declare the size of the array withe positive value as Eran pointed out in his answer . Also have a look at How to initialize an array in Java?

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56