Search code examples
javaarraysprintwriter

How to initialize PrintWriter array?


I have to create n number of files. N is random but it will be in this range 1<=n<=7. When I run this program it gives NullPointException. file_num is number of files to be created. If I remove null from the first line it tells me to initialize the array.

PrintWriter[] writer=null;
for(int j=0;j<file_num;j++)
{
    System.out.println("J is "+j);
    writer[j] =new PrintWriter(new File("file"+(j+1)+".csv"));
}

Solution

  • When I run this program it gives NullPointException.

    That's because

     PrintWriter[] writer = null;
    

    You should initialize writer array with new empty array of size file_num

    PrintWriter[] writer = new PrintWriter[file_num];