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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With