Before you downvote because you perceive this to be another duplicate of "making a static reference to a non-static... ," read the entire question.
I am writing a program that basically goes through a directory and pulls out all of the .txt
files. In fact, I have actually used this
SO thread to help me out. My code has been working except for one thing that isn't covered in the thread. Adding some of the information collected to a HashMap
. In my program, I'm using a HashMap
to store the name as a key and a file bject that I made as a value.
The hash map is as follows:
private HashMap<String, Essay> locations;
This hash map represent the location of each file, along with an object "Essays," which has more information about the file.
My main method contains the logic to see if the file is a txt, and if so, add it to the HashMap
locations.
public void indexEachFile(){
for (File file : directory.listFiles()){
if (file.getName().endsWith(".txt") && file.isFile()){
//If it is a txt
locations.put(File.getName(), new Essay()); //Bad line of code
}
}
}
The line where the name and a new object are added to a hash map throws the error:
Cannot make a static reference to the non-static method getName() from the type File
I completely understand that the function is non-static.
What I don't understand is why the reference to getName()
is static. Is there a better way to implement this addition to the HashMap that doesn't throw the error?
EDIT: Now I realized that my issue stemmed from a small error, which changed what I was trying to do.