0

I have to use the getClass method to access the txt file in the data folder in the project files. However, it gives the following error in the code below:
Cannot make a static reference to the non-static method getClass() from the type Object

public class FileWriting {
     public static void main(String[] args) throws Exception {     
            File file = new File(getClass().getResource("/Data/file.txt").toURI());
            FileWriter writer = new FileWriter(file);  
            BufferedWriter buffer = new BufferedWriter(writer);  
            buffer.write("Welcome to javaTpoint.");  
            buffer.close();  
            System.out.println("Success");  
     }  
}

Is there anything I can use instead of getClass ()? or how do I use getClass () here?

1 Answers1

0

Instead of using getClass() you can use FileWriting.class.

The non-static method getClass() can't be called from the static main method unless you have an instance of the class. You can however get the class in the static context as shown above.

TheChubbyPanda
  • 1,721
  • 2
  • 16
  • 37