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

Time:11-06

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);
    }
}

CodePudding user response:

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

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

CodePudding user response:

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 ca use the method exists like this :

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