1

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);
    }
}
hata
  • 11,633
  • 6
  • 46
  • 69
Belushi
  • 127
  • 1
  • 4

3 Answers3

3

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

boolean ValidPath = new File(path).isDirectory();
hata
  • 11,633
  • 6
  • 46
  • 69
1

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));
Harry Coder
  • 2,429
  • 2
  • 28
  • 32
0

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.

Pallavi
  • 1
  • 1
  • 1