Cannot find symbol File

30,056

Solution 1

Import the File class from the java.io.File package

i.e.

import java.io.File;

Here is documentation for java.io.File and a brief explanation of the File class.

Solution 2

Just add the following statement before the class definition:

import java.io.File;

If you use IDE, like Eclipse, JDeveloper, NetBeans, etc. it can automatilly add the import statement for you.

Solution 3

I think Naveen and Poodle have it right with the need to import the File class

import java.io.File;

Here is another method of getting .dat files that helped me, just FYI =)

It's a general file filtering method that works nicely:

String[] fileList;
File mPath = new File("YOUR_DIRECTORY");
FilenameFilter filter = new FilenameFilter() {
    @Override
    public boolean accept(File dir, String filename) {
        return filename.contains(".dat");
        // you can add multiple conditions for the filer here
    }
};
fileList = mPath.list(filter);
if (fileList == null) {
    //handle no files of type .dat
}

As I said in the comments, you can add multiple conditions to the filter to get specific files. Again, just FYI.

Share:
30,056
user2846960
Author by

user2846960

Updated on May 30, 2020

Comments

  • user2846960
    user2846960 over 2 years

    I'm working on a course project and using this code block my professor gave us to, one, get all files from the current directory and, two, to find which files are in the .dat format. Here is the code block:

    // Get all files from directory
    File curDir = new File(".");
    String[] fileNames = curDir.list();
    ArrayList<String> data = new ArrayList<String>();
    // Find files which may have data. (aka, are in the .dat format)
    for (String s:fileNames)
        if (s.endsWith(".dat"))
            data.add(s);
    

    However, when I try to compile and test my program, I get this error message in response:

    Prog2.java:11: cannot find symbol
    symbol  : class File
    location: class Prog2
       File curDir = new File(".");
       ^
    Prog2.java:11: cannot find symbol
    symbol  : class File
    location: class Prog2
       File curDir = new File(".");
                         ^
    

    I admittedly have minimal experience with the File class, so it might be my fault entirely, but what's up with this?

  • user2846960
    user2846960 over 9 years
    Yep, that did it! That was definitely my fault, I didn't realize it needed an import statement as well. I'm on the vi editor rather than an IDE.
  • Konstantin Yovkov over 9 years
    Then you have to be extremely careful what classes you use. The IDEs provide the developers with great help for this.