Newbie
Newbie

Reputation: 2708

How to know if an agument is a directory or file in Java

I am trying to pass an argument to a method . The argument can be a file or a direcotry.

public class ReadCsv {

    String line =  null;
    BufferedReader br ;

    public void readCsv(String arg) throws Exception{

        File file = new File(arg);
        if(file.isDirectory()){
        for(File dir : file.listFiles()){

                System.out.println(file.getName());
                reader(dir);
            }
        }
        else{
                reader(file);

            }
        }

    public void reader(File file) throws Exception {
        br = new BufferedReader(new FileReader(file));
        while((line=br.readLine())!=null){
            //Code 
    }
}

But the code is not working as I want to. When I pass an argument arg , I have to determine whether it is a file or a directory and work according to it . Can anyone please help me how to determine a file or a directory .This code of mine runs the loop 4 times if arg is a directory.

Upvotes: 0

Views: 99

Answers (4)

Ross Drew
Ross Drew

Reputation: 8246

Your code looks fine, looks like you're just outputting the directory (which you have named 'file') instead of the file, which you have named 'dir'.

for(File dir : file.listFiles()) {
   System.out.println(dir.getName()); //you were outputting file.getName()
}

Upvotes: 1

HybrisHelp
HybrisHelp

Reputation: 5810

Try It .. It print all Directories and file name .

IF Nested Directories :

public class ReadCsv {

    String line =  null;
    BufferedReader br ;

    public void readCsv(String arg) throws Exception{

        File file = new File(arg);
        checkIsDir(file );
    }

    public void checkIsDir(File file) throws Exception {

       if(file.isDirectory()){

            System.out.println("Directory : "file.getName());
            for(File dir : file.listFiles()){
                  checkIsDir(dir);
            }
        }
        else{
                System.out.println("File : "file.getName());
                reader(file);    
            }
    }

    public void reader(File file) throws Exception {
        br = new BufferedReader(new FileReader(file));
        while((line=br.readLine())!=null){
            //Code 
    }
}

Upvotes: 1

Maciej Dobrowolski
Maciej Dobrowolski

Reputation: 12122

See File official documentation. There are methods such as:

isFile();
isDirectory();

Upvotes: 1

Kayaman
Kayaman

Reputation: 73538

File has isDirectory() and isFile() methods you can use to check the type.

Upvotes: 1

Related Questions