lokilindo lokilindo - 3 months ago 13
Java Question

How can I create a new .txt file with the name of the class in which the method was called?

I am new to programming, so let's see if I can explain this well enough.

I am making a Java package. In one of the classes there is a method that creates a file. The name of that file I have it set up as "file.txt", but I want to change it.

Let's say there is a user working on a new project and he imports the library

package
(the one I am working on). I want for the file that is created to take the name of the class in which the user is working on. For example if the user calls it in a class named
Main
, I want the file to be called
main.txt
or
Main.txt
.

If this is not clear enough please let me know, I'll try to explain it better.

Thanks

Edit:
The
getClass().getSimpleName()
doesn't work exactly like I want it to. The method is located inside a library called
library
and the class is called
Main.class
but is being used by a use that imported the library
library
and is working on a class called
SuperMario.class
I want the text file to be called
SuperMario.txt
instead with
getClass().getSimpleName()
applied to my method the file will be called
Main.txt
, because that is the name of the class the method is in. Unfortunately I can't pass the name as a parameter either. Can anyone think of a way around this?

edit: I managed to get the program to behave how I wanted it to, I posted my answer. Thanks for all the comments.

Answer

I solved it, but thank you all for the suggestions. I ended up using Thread.currentThread().getStackTrace()[2].getClassName()

String name = Thread.currentThread().getStackTrace()[2].getClassName();
File file = new File(name + ".txt");

I hope this helps someone else.

Comments