-1

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.

Community
  • 1
  • 1
intboolstring
  • 6,891
  • 5
  • 30
  • 44
  • Possible duplicate of [What is the reason behind "non-static method cannot be referenced from a static context"?](http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – ΦXocę 웃 Пepeúpa ツ Dec 01 '15 at 06:13
  • No matter what your "HashMap problem" is, you are making static references to an instance of the file class.... – ΦXocę 웃 Пepeúpa ツ Dec 01 '15 at 06:14

1 Answers1

2

You need to change the case of 'F' here because you are not referring to file object in the loop iteration. Instead you are using File class, which turns it to a static call.

        locations.put(File.getName(), new Essay()); //Bad line of code

Change like this:

        locations.put(file.getName(), new Essay()); //should be a good line of code now
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136