简体   繁体   中英

this.getClass().getResource(“”).getPath() returns an incorrect path

I am currently making a small simple Java program for my Computer Science Final, which needs to get the path of the current running class. The class files are in the C:\\2013\\game\\ folder.

To get this path, I call this code segment in my main class constructor:

public game(){
    String testPath = this.getClass().getResource("").getPath();
    //Rest of game
}

However, this command instead returns this String: "/" despite the correct output being "C:/2013/game" Additionally, I attempted to rectify this by using this code:

public game(){
    String testPath = this.getClass().getClassLoader().getResource("").getPath();
}

This returns a NullPointerException, which originates from the fact that getClassLoader() returns null, despite working on my Eclipse IDE. Any Ideas?

If you want to load a file in the same path as the code then I suggest you put it in the same root folder as the code and not the same path as the class.

Reason : class can be inside a jar, data file can be put in same jar but its more difficult to edit and update then.

Also suggest you see the preferences class suggested in comments : http://www.javacodegeeks.com/2011/09/use-javautilprefspreferences-instead-of.html though in some cases I think its okay to have your own data/ excel/csv/ java.util.Properties file

Not sure about why it is working in eclipse but I would suggest you focus on running it from a command prompt/ terminal as that is the 'real mode' when it goes live

You could just ask for your class

    String s = getClass().getName();
    int i = s.lastIndexOf(".");
    if(i > -1) s = s.substring(i + 1);
    s = s + ".class";
    System.out.println("name " +s);
    Object testPath = this.getClass().getResource(s);
    System.out.println(testPath);

This will give you

name TstPath.class file:/java/Projects/tests3b/build/classes/s/TstPath.class

Which is my eclipse build path ...

need to parse this to get the path where the class was loaded.

Remember:

  1. App could be started from elsewhere
  2. class can be in jar then path will be different (will point to a jar and file inside that
  3. classpaths can be many at runtime and point 1
  4. a class might be made at runtime via network/ Proxy / injection etc and thus not have a file source, so this is not a generic solution.
  5. think what you want to acheive at a higher level and post that question. meaning why do you want this path?
  6. do you want the app path :-

    File f = new File("./");
    f.getCanonicalPath();//...

So an app can be started from folder c:\\app1\\run\\

The jar could be at c:\\app1\\libsMain\\myapp.jar

and a helper jar could be at c:\\commonlibs\\set1

So this will only tell you where the JVM found your class, that may or maynot be what you need.

if inside a jar will give you some thing like this in unix or windows

jar:file:c:\\app\\my.jar!/s/TstPath.class

If package is s and class is TstPath, you can be sure this will work as the class has to be there ...

now to parse this you can look for your class name and remove / or \\ till you get path you want. String lastIndexOf will help

您可以使用 :

URL classURL = getClass().getProtectionDomain().getCodeSource().getLocation();
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));

also

Test.class.getProtectionDomain().getCodeSource().getLocation().getPath());

The call to getResource([String]) requires a path relative to the folder that contains the class it is being called from. So, if you have the following, anything you pass into MyClass.class.getResource([path]); must be a valid path relative to the com/putable/ package folder and it must point to a real file:

package com.putable;

public class MyClass{}

Using the empty string simply isn't valid, because there can never be a file name that equals the empty string. But, you could do getResource(getClass().getSimpleName()) . Just remove the file name from the end of the path returned by that call and you will have the class directory you want.

Try this.

import java.io.File;

public class TT {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String path = TT.class.getResource("").getPath();
        File file = new File(path);
        System.out.println(file.getAbsolutePath());

    }

}

Try use this code

public game()
{  
    String className = this.getClass().getSimpleName();  
    String testPath = this.getClass().getResource(className+".class");  
    System.out.println("Current Running Location is :"+testPath);   
}

visit the link for more information Find where java class is loaded from

Print out absolute path for a file in your classpath ie build/resources/main/someFileInClassPath.txt Disclaimer, this is similar to another solution on this page that used TT.class..., but this did not work for me instead TT..getClassLoader()... did work for me.

import java.io.File;

public class TT {

    /**
     * @param args
     */
    public static void main(String[] args) {    
        String path = TT.getClassLoader().getResource("someFileInClassPath.txt").getPath();
        File file = new File(path);
        System.out.println(file.getAbsolutePath());

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM