package display;

import java.io.File;

class display 
{
    int file=0, directory=0;
    void list(String path)
    {
        File root = new File(path);
        File[] f1 = root.listFiles();

        for (File S : f1) //error
        {
            if(S.isDirectory())
            {
                list(S.getAbsolutePath());//error
                directory++;                
            }           
            else if(S.isFile())
            {
            file++;
            }
        }
    }
}

package display;

public class displaymain 
{
    public static void main(String[] args)
    {
        display d = new display();
        d.list("d:\\");// error
        System.out.println("No. of directories = "+d.directory);
        System.out.println("No. of files = "+d.file);
    }
}

this is my program for counting files and folders. when i enter address of a folder it works fine but but when i enter a drive it gives error.

output

Exception in thread "main" java.lang.NullpointerException

package com.file.create;

import java.io.File;


public class displaymain 
{
    public static void main(String[] args)
    {
        display d = new display();
        d.list("D:/");// error
        System.out.println("No. of directories = "+d.directory);
        System.out.println("No. of files = "+d.file);
    }
}
class display 
{
    int file=0, directory=0;
    void list(String path)
    {
        File root = new File(path);
        File[] f1 = root.listFiles();
try{
        for (File S : f1) //error
        {
            if(S.isDirectory())
            {
                list(S.getAbsolutePath());//error
                directory++;                
            }           
            else if(S.isFile())
            {
            file++;
            }
        }
}
catch(Exception e)
{
    e.printStackTrace();
    System.out.println(directory);
}
    }
}

See it is counting proper files and directory but it is throwing exception.Just surround the code in try-catch block n handle exception.

the exception is caused due to "D:\System Volume Information" folder in drive that contains drive restore points.
to chk this use :-

void list(String path)
    {
        File root = new File(path);
        File[] f1 = root.listFiles();

        for (File S : f1) //error
        {try{
            if(S.isDirectory())
            {
                list(S.getAbsolutePath());//error
                directory++;                
            }           
            else if(S.isFile())
            {
            file++;
            }
        }catch(Exception e)
            {
                e.printStackTrace();
                System.out.println(S.getAbsolutePath());
            }
        }


    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.