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

后端 未结 7 913
灰色年华
灰色年华 2021-02-05 17:45

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\\g

7条回答
  •  长发绾君心
    2021-02-05 18:05

    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.

提交回复
热议问题