Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find symbol File

Tags:

java

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?

like image 826
user2846960 Avatar asked Oct 04 '13 14:10

user2846960


People also ask

How do I fix error Cannot find symbol?

In the above program, "Cannot find symbol" error will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum.

What is Cannot find symbol?

The cannot find symbol error, also found under the names of symbol not found and cannot resolve symbol , is a Java compile-time error which emerges whenever there is an identifier in the source code which the compiler is unable to work out what it refers to.


3 Answers

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.

like image 93
Naveen Kumar Alone Avatar answered Oct 16 '22 12:10

Naveen Kumar Alone


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.

like image 34
Konstantin Yovkov Avatar answered Oct 16 '22 13:10

Konstantin Yovkov


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.

like image 30
AnxGotta Avatar answered Oct 16 '22 11:10

AnxGotta