• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get the filename of the java file ?  RSS feed

 
Roger Chaosway
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,

How can I retrieve the "filename" of the "current" file in which my java code resides.
That is, I have a java source file - "abc.java" on some "c//xyz//" path. I want to pass the filename "abc.java" to a String during the execution of code.
Could this method be applied inside a scriptlet in a JSP file too?

Roger
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the JavaRanch.
There's one thing wrong with your plan: The java virtual machine executes .class files. It does not necessarily have access to the corresponding .java files. That said, should some file be accessible on the classpath, one could use Class.getResource() to locate it.
 
Roger Chaosway
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Joe,

Thanks a lot for responding.
For some reason, I was unable to phrase the question correctly; I was in a hurry. I apologize.
Actually, the scenario goes something like this -
I am creating dynamic JSPs with on-the-fly names. The name of the JSP is not under my control as it is created in real-time (scalable app). One of my co-programmers require the name of the JSP created assigned to a 'String' variable inside that JSP's scriptlet. Also, the name could not be passed from our "JSP creating logic" to the "created JSPs". For that reason, I was prompted to ask if there is anyway we can get the name of the source JSP file during its execution. The container we are using is Tomcat.
Anyway, I used the following method to get the name of the JSP file in a scriptlet -
///////////////////////////////////////////////////////////////////////

// This string will have the filename of the compiled JSP file.
String compiledJspName = this.getClass().getName();
// The compiled JSPs are created with the pattern - "org.apache.jsp.XXXXX_jsp".
// So I just have to retrieve the XXXXX part.
int startOfName = 15; // Leave out "org.apache.jsp." from the start
int endOfName = compiledJspName.length() - 4; // Leave out "_jsp" from the end
// We are left with the JSP file name (the compiled class actually).
String theJspFileName = compiledJspName.substring(startOfName,endOfName);

///////////////////////////////////////////////////////////////////////

Good thing is, it's working on our framework.
If you think it could be improved please let me know, or comment on any inefficient coding.
Could Class.getResource() be used here ? If so, can you detail me ?

BTW, Javaranch rocks. It's good to be here. :-)

Roger
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!