Java get file path of current class12/26/2023 This works (as tested) with both URLClassLoader and the system class loader. If (StringUtils.startsWith(s, "jar:", true) & s.endsWith("!"))ġ) getShortName returns the class name without the package.Ģ) you can try to convert the URL to a File using "new File(url.toURI())" s is now the URL of the location, but possibly with jar: in front and S = s.substring(0, s.length() - end.length()) If that's also not present just return null s most likely ends with a /, then the full class name with. A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. ![]() URL url = c.getResource(getShortName(c) + ".class") These methods use the current classloader in order to find files, so they have the most flexibility. Public static URL getClassLocation(Class c) class file itself can mostly also be treated as a resource: Another thing to note here is that the above method works only for absolute paths. ![]() At the appropriate time, you can use the methods in the Files class to check the existence of the file corresponding to the Path, create the file, open it, delete it, change its permissions, and so on. There is a trick that works with MOST class loaders not all though. The following code snippet will do this for you: final File f new File(M圜().getCodeSource().getLocation().getPath()). Or indirectly through a specified class: return new ClassPathResource( 'data/employees.dat', ()) Note that from Resource, we can easily jump to Java standard representations like InputStream or File. You can create a Path instance and manipulate it in various ways: you can append to it, extract pieces of it, compare it to another path. As the file URL format on different operating systems may differ, well extract the file.jar part, convert it back to a URL object, and use the Paths class to get the path as a String. That won't work if the JAR file is run from another location. As we can see, the full path of the JAR file lies in the middle of the URL string.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |