Why I am getting error "cannot find symbol" when I would like to use java.io.File class?

Viewed 312

I'd like to use isDirectory() method (java.io.File class). I created a simple test code to try out this method, however I always get a 'cannot find symbol' error.

My code:

import java.io.File;

public class MyUtils {
    public static void main(String[] args) {
        String path = "/this/is/not/a/valid/path";
        boolean ValidPath = path.isDirectory();
        System.out.println(ValidPath);
    }
}
3 Answers

Because your path is a String object. You may instantiate a File object with the path String:

boolean ValidPath = new File(path).isDirectory();

This happens because path is an instance type String and isDirectory is not a method available in the String class. To work with files or directories, you have to use the appropriate classes.

Your code should look like this :

import java.nio.file.Files;
import java.nio.file.Paths;

public class MyUtils {
    public static void main(String[] args) {
        String path = "/this/is/not/a/valid/path";
        boolean isValidPath = Files.isDirectory(Paths.get(path));
        System.out.println(isValidPath);
    }
}

The ValidPath should be renamed to isValidPath.

As you want to check the validity of your path, you can use the method exists like this :

boolean isValidPath = Files.exists(Paths.get(path));

It is because, isDirectory is a method of java.io.Files class, it must be called by a File object, but you are trying to invoke the method using a string object.

Create a File obj like: new File(path), the call isDirectory() method.

Related