Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Get path of current executing class

  1. #1
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Question Get path of current executing class

    Yall doing good today forum?

    I've got a question for you.
    I've been through a lot of reading and Google-ing but I haven't been able to find what I need.

    The nature of this problem is not sintax, or logical. Its the lack of knowledge.

    I am using a method that returns the absolute path, different from what the file object provides, because I don't know how to create a file object of an existing file (at any given path) for itself (.class) to easily gain the abbilities of getPath(), getAbsolutePath(), or getCanonicalPath().

    If you've got any ideas how to do this would be wonderful.

    So here is what I've been using..

    	private static String parentPath(){
    	    return (System.getProperty("user.dir") + "\\" + Thread.currentThread().getStackTrace()[1].getClassName() + ".class");
    	}
     
    	private static String javaPath(){
    	    System.out.print("GENERATION: " + generation + ", JAVA PATH: " + System.getProperty("user.dir") + "\\" + Thread.currentThread().getStackTrace()[1].getClassName() + ".java".replace("\\", "\\\\")); // S.O.P. CHECKPOINT
    	    return (System.getProperty("user.dir") + "\\" + Thread.currentThread().getStackTrace()[1].getClassName() + ".java".replace("\\", "\\\\"));
    	}

    ..in order to obtain the absolute path of the current class' .java file.

    The part of the code not returning what I need is

    System.getProperty("user.dir").

    Summarizing briefly, I've got a working program that makes two copies of itself, with random names, compiles, and executes them again. (of course I've placed some safegaurds to avoid infite looping).

    The are some methods in the program that require their own .java. In order to do that, first I need to send the correct path. So what it does, it obtains it's current path and name. Obtaining its own name is a piece of cake, but obtaining is own path a different story #APieceOfDifficultCake. After obtaining path and name I parse both of them and add ".java" at the end.

    System.getProperty("user.dir") seems to be returning the original path of the very first class "Earth" which is at C:\Users\Andrew\Desktop\, and continues to send that directory in the other two programs, instead of their own directory. SEE OUTPUT BELOW.

    C:\Users\Andrew\Desktop>java Earth
    GENERATION: 0, JAVA PATH: C:\Users\Andrew\Desktop\Earth.javaOUT: GENERATION: 1, JAVA PATH: C:\Users\Andrew\Desktop\zxrhgzu.javaERR: Error: Could not find or load main class exmwvbq
    OUT: GENERATION: 1, JAVA PATH: C:\Users\Andrew\Desktop\zxrhgzu.javaERR: Error: Could not find or load main class nqylylo
    ERR: java.io.FileNotFoundException: C:\Users\Andrew\Desktop\zxrhgzu.java (The system cannot find the file specified)
    ERR: at java.io.FileInputStream.open(Native Method)
    ERR: at java.io.FileInputStream.<init>(Unknown Source)
    ERR: at java.io.FileReader.<init>(Unknown Source)
    ERR: at zxrhgzu.replicate(zxrhgzu.java:64)
    ERR: at zxrhgzu.create(zxrhgzu.java:52)
    ERR: at zxrhgzu.newStandAlone(zxrhgzu.java:113)
    ERR: at zxrhgzu.mitosis(zxrhgzu.java:118)
    ERR: at zxrhgzu.main(zxrhgzu.java:131)
    ERR: java.io.FileNotFoundException: C:\Users\Andrew\Desktop\zxrhgzu.java (The system cannot find the file specified)
    ERR: at java.io.FileInputStream.open(Native Method)
    ERR: at java.io.FileInputStream.<init>(Unknown Source)
    ERR: at java.io.FileReader.<init>(Unknown Source)
    ERR: at zxrhgzu.replicate(zxrhgzu.java:64)
    ERR: at zxrhgzu.create(zxrhgzu.java:52)
    ERR: at zxrhgzu.newStandAlone(zxrhgzu.java:113)
    ERR: at zxrhgzu.mitosis(zxrhgzu.java:118)
    ERR: at zxrhgzu.main(zxrhgzu.java:131)
    GENERATION: 0, JAVA PATH: C:\Users\Andrew\Desktop\Earth.javaOUT: GENERATION: 1, JAVA PATH: C:\Users\Andrew\Desktop\xwnbosk.javaERR: Error: Could not find or load main class covlpvu
    OUT: GENERATION: 1, JAVA PATH: C:\Users\Andrew\Desktop\xwnbosk.javaERR: Error: Could not find or load main class keazzov
    ERR: java.io.FileNotFoundException: C:\Users\Andrew\Desktop\xwnbosk.java (The system cannot find the file specified)
    ERR: at java.io.FileInputStream.open(Native Method)
    ERR: at java.io.FileInputStream.<init>(Unknown Source)
    ERR: at java.io.FileReader.<init>(Unknown Source)
    ERR: at xwnbosk.replicate(xwnbosk.java:64)
    ERR: at xwnbosk.create(xwnbosk.java:52)
    ERR: at xwnbosk.newStandAlone(xwnbosk.java:113)
    ERR: at xwnbosk.mitosis(xwnbosk.java:118)
    ERR: at xwnbosk.main(xwnbosk.java:131)
    ERR: java.io.FileNotFoundException: C:\Users\Andrew\Desktop\xwnbosk.java (The system cannot find the file specified)
    ERR: at java.io.FileInputStream.open(Native Method)
    ERR: at java.io.FileInputStream.<init>(Unknown Source)
    ERR: at java.io.FileReader.<init>(Unknown Source)
    ERR: at xwnbosk.replicate(xwnbosk.java:64)
    ERR: at xwnbosk.create(xwnbosk.java:52)
    ERR: at xwnbosk.newStandAlone(xwnbosk.java:113)
    ERR: at xwnbosk.mitosis(xwnbosk.java:118)
    ERR: at xwnbosk.main(xwnbosk.java:131)
    If you see ie Could not find or load main class covlpvu its because when its time to compile the file, its got no code in it, ultimately because the path given to the method that accesses the java file is incorrect, thus not letting it write the java code.

    I would really appreciate some feedback.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,260
    Thanks
    176
    Thanked 818 Times in 761 Posts
    Blog Entries
    5

    Default Re: Get path of current executing class

    Does not creating a File object and getting its absolute path work?

    File file = new File("temp");
    System.out.println(file.getAbsolutePath());
    System.out.println(file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 4);///remove the 'temp' file name to get the containing directory

  3. The Following User Says Thank You to copeg For This Useful Post:

    Andrew R (August 25th, 2013)

  4. #3
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Get path of current executing class

    that is just very clever!

    I never thought about that. I'll have to look at the substring() afterwards, it could be very useful.

    I've been looking real hard but its actually much easier way than I thought.
    I'll try that see how it goes.

    Off Topic: By the way, there was some low leveled seismic activity 30 min ago Honduras.

    --- Update ---

    I've updated the code. Everything seems to be working great, except in one place.

    The value returned by what you've posted persists to show the original directory of the first program.

    See post #7
    Keeps returning the original address.

    	private static String parentPath() { return (getOwnDir() + getOwnName() + ".class"); }
     
    	private static String javaPath() { return (getOwnDir() + getOwnName() + ".java"); }
     
    	private static String getOwnName() { return (Thread.currentThread().getStackTrace()[1].getClassName()); }
     
    	private static String getOwnDir() { 
    	    File f = new File("temp");       
    		String local = f.getAbsolutePath().substring(0,f.getAbsolutePath().length()-4);
    		try { if(f.exists()) if(f.isFile()) f.delete(); } catch (Exception e){ e.printStackTrace(); }
    		return local;
    	}

  5. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,260
    Thanks
    176
    Thanked 818 Times in 761 Posts
    Blog Entries
    5

    Default Re: Get path of current executing class

    Are you working inside a package? The File method will create a file relative to the root of your package, so if you have:
    C:\MyDir\mypackage\myclass.class
    getAbsolutePath of this will return C\MyDir\temp

  6. #5
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Get path of current executing class

    No I haven't. From what I know about package I wouldn't have any need for it. Packages are just to keep collaborating class organized. This program is intended to be "Stand Alone" thus wouldn't be necessary to add a package.

    I think I know a work around this problem, by having the path the program has selected to create the copies to be written in thier code passing on the paramenters without having the copies self determining their location. Prolly that'd work but I wish I could have the copies determine it themselves.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,075
    Thanks
    47
    Thanked 2,147 Times in 2,120 Posts

    Default Re: Get path of current executing class

    persists to show the original directory of the first program.
    Could you extract from the output the lines that show what you are talking about?
    Also add some comments showing what you want the output to be.

    And post the code that is creating the output.

    to obtain the absolute path of the current class' .java file
    There does not need to be any connection between the location of a class's .java file and its .class file. They can be anywhere. In fact the .java file could have been erased.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Get path of current executing class

    @Norm

    Just for reference:

    	private static String javaPath(){
    	    System.out.print("GENERATION: " + generation + ", JAVA PATH: " + System.getProperty("user.dir") + "\\" + Thread.currentThread().getStackTrace()[1].getClassName() + ".java".replace("\\", "\\\\")); // S.O.P. CHECKPOINT
    	    return (System.getProperty("user.dir") + "\\" + Thread.currentThread().getStackTrace()[1].getClassName() + ".java".replace("\\", "\\\\"));
    	}


    Ouput generated by java = javaPath(); System.out.print(java); =
    C:\Users\Andrew\Desktop\Earth.java <----- This one is good
    C:\Users\Andrew\Desktop\dowgpec.java <---- Not Good
    C:\Users\Andrew\Desktop\sieavdh.java <---- Not Good
    my original is located here: C:\Users\Andrew\Desktop\Earth.java
    the other copies are created at C:\, not C:\Users\Andrew\Desktop\

    Correct output should be like this:

    C:\Users\Andrew\Desktop\Earth.java
    C:\dowgpec.java
    C:\sieavdh.java
    Since the path received is not correct, I am given the following result per program :

    ERR: java.io.FileNotFoundException: C:\Users\Andrew\Desktop\dowgpec.java (The system cannot find the file specified)
    ERR: at java.io.FileInputStream.open(Native Method)
    ERR: at java.io.FileInputStream.<init>(Unknown Source)
    ERR: at java.io.FileReader.<init>(Unknown Source) <---- nothing to be read
    ERR: at dowgpec.replicate(dowgpec.java:68) <---- where the method to retrieve code and return as String did not occur
    ERR: at dowgpec.create(dowgpec.java:56) <---- where the writing of the code did not take place
    ERR: at dowgpec.newStandAlone(dowgpec.java:122) <--- where the method that englobes the creation of a copy failed
    ERR: at dowgpec.mitosis(dowgpec.java:127) <--- where the 2 copies are generated and the old class is deleted
    ERR: at dowgpec.main(dowgpec.java:141) <---- where the entire program had to stop

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,075
    Thanks
    47
    Thanked 2,147 Times in 2,120 Posts

    Default Re: Get path of current executing class

    How are the "Not good" paths created?
    How were the three .java files put into the folders where they are located?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Get path of current executing class

    the original one is located here: C:\Users\Andrew\Desktop\
    the other three files are located C:\, regardless of their location the javaPath() method on each program continues to return C:\Users\Andrew\Desktop\ as directory for each of the programs

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,075
    Thanks
    47
    Thanked 2,147 Times in 2,120 Posts

    Default Re: Get path of current executing class

    Why do you think the javaPath() method should return the locations of the .java files?

    How were the .java files put into the folders where they are located? The code that wrote the files should save the location where it wrote them.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Get path of current executing class

    Why do you think the javaPath() method should return the locations of the .java files?
    First, for each copy of the program, the class is created in the same directory its .java was saved on. When executing that program from the shell or cmd prompt is has its own runtime, the class should be able to obtain its own directory, the way I was trying to [ System.getProperty("user.dir") ] or the way copeg showed me. It is completely separate from the original. It should be working, but its not.

    Ideally I would have each program look up its on directory, firstly because I want it to be self-sufficient, "stand alone". Secondly, I wouldn't loke to depend on more variables or lists. I am specially being persistent on it because, I wouldn't like to come to similar situation in the future and end up relying on lists! I want for the program to cut off as much information as it can from its parent program.

    How were the .java files put into the folders where they are located? The code that wrote the files should save the location where it wrote them.
    Like I mentioned, that's also what I've figured out. It's an easy work around, I would prefer not to use.

    Buttomline I just want to figure out why the original directory is returned. Doesn't make any sense. Prolly' I am using it in a way it wasn't ment to be used, and this problem was never forseen. What I am doing is not grandiose, but it is definetly using very little of the object-oriented programming.

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,075
    Thanks
    47
    Thanked 2,147 Times in 2,120 Posts

    Default Re: Get path of current executing class

    the class should be able to obtain its own directory
    Does that mean that you want a class object to find the location of its .class file when it is executing?
    The .class file should be on the classpath when it is executed. The Class class's getResource() method will return an URL for a file/resource on the classpath. Build the filename of the file by adding on ".class" and use the getResource() method. The URL it returns will have the path to the .class file.
    If you don't understand my answer, don't ignore it, ask a question.

  14. The Following User Says Thank You to Norm For This Useful Post:

    Andrew R (August 25th, 2013)

  15. #13
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Get path of current executing class

    That's what I want. I will try that right now. (Good morning btw, I need a cup of coffee)

    --- Update ---

    It works. Thanks for the assistance.

Similar Threads

  1. [SOLVED] Executing cmd from Java, Compiling and Executing IN Runtime
    By Andrew R in forum What's Wrong With My Code?
    Replies: 6
    Last Post: August 9th, 2013, 10:00 AM
  2. File not found in class path
    By Jeff.Steinkamp in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: January 1st, 2013, 07:37 PM
  3. How to load class path for .properties file
    By kewlkeny in forum Web Frameworks
    Replies: 1
    Last Post: January 23rd, 2012, 07:40 AM
  4. Program to print current directory path to the console
    By JavaPF in forum Java Programming Tutorials
    Replies: 1
    Last Post: October 9th, 2009, 12:59 PM
  5. Program to print current directory path to the console
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 1
    Last Post: October 9th, 2009, 12:59 PM