lokilindo lokilindo - 1 year ago 62
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

(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
, I want the file to be called

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


doesn't work exactly like I want it to. The method is located inside a library called
and the class is called
but is being used by a use that imported the library
and is working on a class called
I want the text file to be called
instead with
applied to my method the file will be called
, 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download