Related
Let's have a maven project with resources in following structure:
src/main/resources
dir1
subdir1
files...
subdir2
files...
dir2
Although I found many answers how to list file resources, I am stuck to find a way how to list all direct subdirectories of a directory (or path) in resources, that would work when app is run both from IDE (IntelliJ) and jar.
The goal is to get names of subdirectories of directory "dir1":
subdir1, subdir2
I tried
Thread.currentThread().getContextClassLoader().getResourceAsStream("dir1");
and to use returned InputStream (containing names of subdirectories), but does not work from jar. Works from IntelliJ.
I also tried to use spring framework but
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("dir1/*");
does not work as well from jar - resources array is empty. Works from IntelliJ.
I tried to modify to
Resource[] resources = resolver.getResources("dir1/*/");
and it works from jar, but does not work from IntelliJ.
When I make it work from jar, I break the other way and vice versa. My last idea is to use
Resource[] resources = resolver.getResources("dir1/**");
to get all resources under the directory and then get only ones that are required. Is there a better (preferably not hacky) way?
I finally ended up with this (using spring):
public class ResourceScanner {
private PathMatchingResourcePatternResolver resourcePatternResolver;
public ResourceScanner() {
this.resourcePatternResolver = new PathMatchingResourcePatternResolver();
}
public Resource getResource(String path) {
path = path.replace("\\", "/");
return resourcePatternResolver.getResource(path);
}
public Resource[] getResources(String path) throws IOException {
path = path.replace("\\", "/");
return resourcePatternResolver.getResources(path);
}
public Resource[] getResourcesIn(String path) throws IOException {
// Get root dir URI
Resource root = getResource(path);
String rootUri = root.getURI().toString();
// Search all resources under the root dir
path = (path.endsWith("/")) ? path + "**" : path + "/**";
// Filter only direct children
return Arrays.stream(getResources(path)).filter(resource -> {
try {
String uri = resource.getURI().toString();
boolean isChild = uri.length() > rootUri.length() && !uri.equals(rootUri + "/");
if (isChild) {
boolean isDirInside = uri.indexOf("/", rootUri.length() + 1) == uri.length() - 1;
boolean isFileInside = uri.indexOf("/", rootUri.length() + 1) == -1;
return isDirInside || isFileInside;
}
return false;
} catch (IOException e) {
return false;
}
}).toArray(Resource[]::new);
}
public String[] getResourcesNamesIn(String path) throws IOException {
// Get root dir URI
Resource root = getResource(path);
String rootUri = URLDecoder.decode(root.getURI().toString().endsWith("/") ? root.getURI().toString() : root.getURI().toString() + "/", "UTF-8");
// Get direct children names
return Arrays.stream(getResourcesIn(path)).map(resource -> {
try {
String uri = URLDecoder.decode(resource.getURI().toString(), "UTF-8");
boolean isFile = uri.indexOf("/", rootUri.length()) == -1;
if (isFile) {
return uri.substring(rootUri.length());
} else {
return uri.substring(rootUri.length(), uri.indexOf("/", rootUri.length() + 1));
}
} catch (IOException e) {
return null;
}
}).toArray(String[]::new);
}
}
The problem with a jar is that there are not folder as such, there are entries, and folders are just entries with a trailing slash in it's name. This is probably why dir1/*/ return the folders in jar but not from de IDE where the folder name does not end with /. For a similar reason dir1/* work on the IDE but not in the jar since again, the folder name ends with the slash in the jar.
Spring handles the resources based on files, if you try to get an empty folder as resource it will fail, and this empty folder normally is not added to the jar. Also looking for folders is not that common, since the content is in files, and the only useful information is what files it contains.
The easiest way you can achieve this is to use dir1/** pattern, since this will list all the files, and folders with files under the dir1 directory.
'Detecting' if the program is being executed from a jar file, to choose a different strategy to list the folders can also be done, but that solution is even more 'hacky'.
Here an example using first option, pattern dir1/** (just in case needed):
String folderName = "dir1";
String folderPath = String.format("%s/**", folderName);
Resource[] resources = resolver.getResources(folderPath);
Map<String, Resource> resourceByURI = Arrays.stream(resources)
.collect(Collectors.toMap(resource -> {
try {
return resource.getURI().toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, Function.identity()));
The resourceByURI is a map containing the Resource, identified by its URI.
Resource folder = resolver.getResource(folderName);
int folderLength = folder.getURI().toString().length();
Map<String, String> subdirectoryByName = resourceByURI.keySet().stream()
.filter(name -> name.length() > folderLength
&& name.indexOf("/", folderLength + 1) == name.length() - 1)
.collect(Collectors.toMap(Function.identity(), name -> name.substring(folderLength,
name.indexOf("/", folderLength + 1))));
Then you can get the URI of the folder, to calculate the offset of the path (similar to what spring does), then check that the name is longer that the current folder (to discard the same folder in the jar case) and that the name constains a single / in the end. Finally collect to a Map again identified by the URI, containing the name of the folders. The collection of folder names is subdirectoryByName.values().
Seems like the following works:
public String[] getResourcesNames(String path) {
try {
URL url = getClassLoader().getResource(path);
if (url == null) {
return null;
}
URI uri = url.toURI();
if (uri.getScheme().equals("jar")) { // Run from jar
try (FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap())){
Path resourcePath = fileSystem.getPath(path);
// Get all contents of a resource (skip resource itself), if entry is a directory remove trailing /
List<String> resourcesNames =
Files.walk(resourcePath, 1)
.skip(1)
.map(p -> {
String name = p.getFileName().toString();
if (name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
return name;
})
.sorted()
.collect(Collectors.toList());
return resourcesNames.toArray(new String[resourcesNames.size()]);
}
} else { // Run from IDE
File resource = new File(uri);
return resource.list();
}
} catch (IOException | URISyntaxException e) {
return null;
}
}
private ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
Thanks Lubik for your first post, it works very well within Springboot 2.1., in IDE or jar.
I needed to copy and read some resources files from jar (or IDE in dev), returning Resource[] instead, next copy them where you want on the disk thanks to resource.getInputStream():
for (Resource resource: mapResources) {
Path destPath =
someFolder.resolve(resource.getFilename());
Files.copy(resource.getInputStream(), destPath);
}
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.
So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
Replace "MyClass" with the name of your class.
Obviously, this will do odd things if your class was loaded from a non-file location.
Best solution for me:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
This should solve the problem with spaces and special characters.
To obtain the File for a given Class, there are two steps:
Convert the Class to a URL
Convert the URL to a File
It is important to understand both steps, and not conflate them.
Once you have the File, you can call getParentFile to get the containing folder, if that is what you need.
Step 1: Class to URL
As discussed in other answers, there are two major ways to find a URL relevant to a Class.
URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation();
URL url = Bar.class.getResource(Bar.class.getSimpleName() + ".class");
Both have pros and cons.
The getProtectionDomain approach yields the base location of the class (e.g., the containing JAR file). However, it is possible that the Java runtime's security policy will throw SecurityException when calling getProtectionDomain(), so if your application needs to run in a variety of environments, it is best to test in all of them.
The getResource approach yields the full URL resource path of the class, from which you will need to perform additional string manipulation. It may be a file: path, but it could also be jar:file: or even something nastier like bundleresource://346.fwk2106232034:4/foo/Bar.class when executing within an OSGi framework. Conversely, the getProtectionDomain approach correctly yields a file: URL even from within OSGi.
Note that both getResource("") and getResource(".") failed in my tests, when the class resided within a JAR file; both invocations returned null. So I recommend the #2 invocation shown above instead, as it seems safer.
Step 2: URL to File
Either way, once you have a URL, the next step is convert to a File. This is its own challenge; see Kohsuke Kawaguchi's blog post about it for full details, but in short, you can use new File(url.toURI()) as long as the URL is completely well-formed.
Lastly, I would highly discourage using URLDecoder. Some characters of the URL, : and / in particular, are not valid URL-encoded characters. From the URLDecoder Javadoc:
It is assumed that all characters in the encoded string are one of the following: "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "*". The character "%" is allowed but is interpreted as the start of a special escaped sequence.
...
There are two possible ways in which this decoder could deal with illegal strings. It could either leave illegal characters alone or it could throw an IllegalArgumentException. Which approach the decoder takes is left to the implementation.
In practice, URLDecoder generally does not throw IllegalArgumentException as threatened above. And if your file path has spaces encoded as %20, this approach may appear to work. However, if your file path has other non-alphameric characters such as + you will have problems with URLDecoder mangling your file path.
Working code
To achieve these steps, you might have methods like the following:
/**
* Gets the base location of the given class.
* <p>
* If the class is directly on the file system (e.g.,
* "/path/to/my/package/MyClass.class") then it will return the base directory
* (e.g., "file:/path/to").
* </p>
* <p>
* If the class is within a JAR file (e.g.,
* "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
* path to the JAR (e.g., "file:/path/to/my-jar.jar").
* </p>
*
* #param c The class whose location is desired.
* #see FileUtils#urlToFile(URL) to convert the result to a {#link File}.
*/
public static URL getLocation(final Class<?> c) {
if (c == null) return null; // could not load the class
// try the easy way first
try {
final URL codeSourceLocation =
c.getProtectionDomain().getCodeSource().getLocation();
if (codeSourceLocation != null) return codeSourceLocation;
}
catch (final SecurityException e) {
// NB: Cannot access protection domain.
}
catch (final NullPointerException e) {
// NB: Protection domain or code source is null.
}
// NB: The easy way failed, so we try the hard way. We ask for the class
// itself as a resource, then strip the class's path from the URL string,
// leaving the base path.
// get the class's raw resource path
final URL classResource = c.getResource(c.getSimpleName() + ".class");
if (classResource == null) return null; // cannot find class resource
final String url = classResource.toString();
final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
if (!url.endsWith(suffix)) return null; // weird URL
// strip the class's path from the URL string
final String base = url.substring(0, url.length() - suffix.length());
String path = base;
// remove the "jar:" prefix and "!/" suffix, if present
if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);
try {
return new URL(path);
}
catch (final MalformedURLException e) {
e.printStackTrace();
return null;
}
}
/**
* Converts the given {#link URL} to its corresponding {#link File}.
* <p>
* This method is similar to calling {#code new File(url.toURI())} except that
* it also handles "jar:file:" URLs, returning the path to the JAR file.
* </p>
*
* #param url The URL to convert.
* #return A file path suitable for use with e.g. {#link FileInputStream}
* #throws IllegalArgumentException if the URL does not correspond to a file.
*/
public static File urlToFile(final URL url) {
return url == null ? null : urlToFile(url.toString());
}
/**
* Converts the given URL string to its corresponding {#link File}.
*
* #param url The URL to convert.
* #return A file path suitable for use with e.g. {#link FileInputStream}
* #throws IllegalArgumentException if the URL does not correspond to a file.
*/
public static File urlToFile(final String url) {
String path = url;
if (path.startsWith("jar:")) {
// remove "jar:" prefix and "!/" suffix
final int index = path.indexOf("!/");
path = path.substring(4, index);
}
try {
if (PlatformUtils.isWindows() && path.matches("file:[A-Za-z]:.*")) {
path = "file:/" + path.substring(5);
}
return new File(new URL(path).toURI());
}
catch (final MalformedURLException e) {
// NB: URL is not completely well-formed.
}
catch (final URISyntaxException e) {
// NB: URL is not completely well-formed.
}
if (path.startsWith("file:")) {
// pass through the URL as-is, minus "file:" prefix
path = path.substring(5);
return new File(path);
}
throw new IllegalArgumentException("Invalid URL: " + url);
}
You can find these methods in the SciJava Common library:
org.scijava.util.ClassUtils
org.scijava.util.FileUtils.
You can also use:
CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
Use ClassLoader.getResource() to find the URL for your current class.
For example:
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
(This example taken from a similar question.)
To find the directory, you'd then need to take apart the URL manually. See the JarClassLoader tutorial for the format of a jar URL.
I'm surprised to see that none recently proposed to use Path. Here follows a citation: "The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path"
Thus, a good alternative is to get the Path objest as:
Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());
The only solution that works for me on Linux, Mac and Windows:
public static String getJarContainingFolder(Class aclass) throws Exception {
CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
File jarFile;
if (codeSource.getLocation() != null) {
jarFile = new File(codeSource.getLocation().toURI());
}
else {
String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
jarFile = new File(jarFilePath);
}
return jarFile.getParentFile().getAbsolutePath();
}
If you are really looking for a simple way to get the folder in which your JAR is located you should use this implementation.
Solutions like this are hard to find and many solutions are no longer supported, many others provide the path of the file instead of the actual directory. This is easier than other solutions you are going to find and works for java version 1.12.
new File(".").getCanonicalPath()
Gathering the Input from other answers this is a simple one too:
String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\";
Both will return a String with this format:
"C:\Users\User\Desktop\Folder\"
In a simple and concise line.
I had the the same problem and I solved it that way:
File currentJavaJarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
String currentRootDirectoryPath = currentJavaJarFilePath.replace(currentJavaJarFile.getName(), "");
I hope I was of help to you.
Here's upgrade to other comments, that seem to me incomplete for the specifics of
using a relative "folder" outside .jar file (in the jar's same
location):
String path =
YourMainClassName.class.getProtectionDomain().
getCodeSource().getLocation().getPath();
path =
URLDecoder.decode(
path,
"UTF-8");
BufferedImage img =
ImageIO.read(
new File((
new File(path).getParentFile().getPath()) +
File.separator +
"folder" +
File.separator +
"yourfile.jpg"));
For getting the path of running jar file I have studied the above solutions and tried all methods which exist some difference each other. If these code are running in Eclipse IDE they all should be able to find the path of the file including the indicated class and open or create an indicated file with the found path.
But it is tricky, when run the runnable jar file directly or through the command line, it will be failed as the path of jar file gotten from the above methods will give an internal path in the jar file, that is it always gives a path as
rsrc:project-name (maybe I should say that it is the package name of the main class file - the indicated class)
I can not convert the rsrc:... path to an external path, that is when run the jar file outside the Eclipse IDE it can not get the path of jar file.
The only possible way for getting the path of running jar file outside Eclipse IDE is
System.getProperty("java.class.path")
this code line may return the living path (including the file name) of the running jar file (note that the return path is not the working directory), as the java document and some people said that it will return the paths of all class files in the same directory, but as my tests if in the same directory include many jar files, it only return the path of running jar (about the multiple paths issue indeed it happened in the Eclipse).
Other answers seem to point to the code source which is Jar file location which is not a directory.
Use
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
the selected answer above is not working if you run your jar by click on it from Gnome desktop environment (not from any script or terminal).
Instead, I have fond that the following solution is working everywhere:
try {
return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
I had to mess around a lot before I finally found a working (and short) solution.
It is possible that the jarLocation comes with a prefix like file:\ or jar:file\, which can be removed by using String#substring().
URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();
For the jar file path:
String jarPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
For getting the directory path of that jar file:
String dirPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getParent();
The results of the two lines above are like this:
/home/user/MyPrograms/myapp/myjar.jar (value of jarPath)
/home/user/MyPrograms/myapp (value of dirPath)
public static String dir() throws URISyntaxException
{
URI path=Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
String name= Main.class.getPackage().getName()+".jar";
String path2 = path.getRawPath();
path2=path2.substring(1);
if (path2.contains(".jar"))
{
path2=path2.replace(name, "");
}
return path2;}
Works good on Windows
I tried to get the jar running path using
String folder = MyClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();
c:\app>java -jar application.jar
Running the jar application named "application.jar", on Windows in the folder "c:\app", the value of the String variable "folder" was "\c:\app\application.jar" and I had problems testing for path's correctness
File test = new File(folder);
if(file.isDirectory() && file.canRead()) { //always false }
So I tried to define "test" as:
String fold= new File(folder).getParentFile().getPath()
File test = new File(fold);
to get path in a right format like "c:\app" instead of "\c:\app\application.jar" and I noticed that it work.
The simplest solution is to pass the path as an argument when running the jar.
You can automate this with a shell script (.bat in Windows, .sh anywhere else):
java -jar my-jar.jar .
I used . to pass the current working directory.
UPDATE
You may want to stick the jar file in a sub-directory so users don't accidentally click it. Your code should also check to make sure that the command line arguments have been supplied, and provide a good error message if the arguments are missing.
Actually here is a better version - the old one failed if a folder name had a space in it.
private String getJarFolder() {
// get name and path
String name = getClass().getName().replace('.', '/');
name = getClass().getResource("/" + name + ".class").toString();
// remove junk
name = name.substring(0, name.indexOf(".jar"));
name = name.substring(name.lastIndexOf(':')-1, name.lastIndexOf('/')+1).replace('%', ' ');
// remove escape characters
String s = "";
for (int k=0; k<name.length(); k++) {
s += name.charAt(k);
if (name.charAt(k) == ' ') k += 2;
}
// replace '/' with system separator char
return s.replace('/', File.separatorChar);
}
As for failing with applets, you wouldn't usually have access to local files anyway. I don't know much about JWS but to handle local files might it not be possible to download the app.?
String path = getClass().getResource("").getPath();
The path always refers to the resource within the jar file.
Try this:
String path = new File("").getAbsolutePath();
This code worked for me to identify if the program is being executed inside a JAR file or IDE:
private static boolean isRunningOverJar() {
try {
String pathJar = Application.class.getResource(Application.class.getSimpleName() + ".class").getFile();
if (pathJar.toLowerCase().contains(".jar")) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
If I need to get the Windows full path of JAR file I am using this method:
private static String getPathJar() {
try {
final URI jarUriPath =
Application.class.getResource(Application.class.getSimpleName() + ".class").toURI();
String jarStringPath = jarUriPath.toString().replace("jar:", "");
String jarCleanPath = Paths.get(new URI(jarStringPath)).toString();
if (jarCleanPath.toLowerCase().contains(".jar")) {
return jarCleanPath.substring(0, jarCleanPath.lastIndexOf(".jar") + 4);
} else {
return null;
}
} catch (Exception e) {
log.error("Error getting JAR path.", e);
return null;
}
}
My complete code working with a Spring Boot application using CommandLineRunner implementation, to ensure that the application always be executed within of a console view (Double clicks by mistake in JAR file name), I am using the next code:
#SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) throws IOException {
Console console = System.console();
if (console == null && !GraphicsEnvironment.isHeadless() && isRunningOverJar()) {
Runtime.getRuntime().exec(new String[]{"cmd", "/c", "start", "cmd", "/k",
"java -jar \"" + getPathJar() + "\""});
} else {
SpringApplication.run(Application.class, args);
}
}
#Override
public void run(String... args) {
/*
Additional code here...
*/
}
private static boolean isRunningOverJar() {
try {
String pathJar = Application.class.getResource(Application.class.getSimpleName() + ".class").getFile();
if (pathJar.toLowerCase().contains(".jar")) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
private static String getPathJar() {
try {
final URI jarUriPath =
Application.class.getResource(Application.class.getSimpleName() + ".class").toURI();
String jarStringPath = jarUriPath.toString().replace("jar:", "");
String jarCleanPath = Paths.get(new URI(jarStringPath)).toString();
if (jarCleanPath.toLowerCase().contains(".jar")) {
return jarCleanPath.substring(0, jarCleanPath.lastIndexOf(".jar") + 4);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
}
Something that is frustrating is that when you are developing in Eclipse MyClass.class.getProtectionDomain().getCodeSource().getLocation() returns the /bin directory which is great, but when you compile it to a jar, the path includes the /myjarname.jar part which gives you illegal file names.
To have the code work both in the ide and once it is compiled to a jar, I use the following piece of code:
URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
myFile = new File(applicationRootPath, "filename");
}
else{
myFile = new File(applicationRootPath.getParentFile(), "filename");
}
Not really sure about the others but in my case it didn't work with a "Runnable jar" and i got it working by fixing codes together from phchen2 answer and another from this link :How to get the path of a running JAR file?
The code:
String path=new java.io.File(Server.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getAbsolutePath();
path=path.substring(0, path.lastIndexOf("."));
path=path+System.getProperty("java.class.path");
Have tried several of the solutions up there but none yielded correct results for the (probably special) case that the runnable jar has been exported with "Packaging external libraries" in Eclipse. For some reason all solutions based on the ProtectionDomain do result in null in that case.
From combining some solutions above I managed to achieve the following working code:
String surroundingJar = null;
// gets the path to the jar file if it exists; or the "bin" directory if calling from Eclipse
String jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath()).getAbsolutePath();
// gets the "bin" directory if calling from eclipse or the name of the .jar file alone (without its path)
String jarFileFromSys = System.getProperty("java.class.path").split(";")[0];
// If both are equal that means it is running from an IDE like Eclipse
if (jarFileFromSys.equals(jarDir))
{
System.out.println("RUNNING FROM IDE!");
// The path to the jar is the "bin" directory in that case because there is no actual .jar file.
surroundingJar = jarDir;
}
else
{
// Combining the path and the name of the .jar file to achieve the final result
surroundingJar = jarDir + jarFileFromSys.substring(1);
}
System.out.println("JAR File: " + surroundingJar);
The above methods didn't work for me in my Spring environment, since Spring shades the actual classes into a package called BOOT-INF, thus not the actual location of the running file. I found another way to retrieve the running file through the Permissions object which have been granted to the running file:
public static Path getEnclosingDirectory() {
return Paths.get(FileUtils.class.getProtectionDomain().getPermissions()
.elements().nextElement().getName()).getParent();
}
Mention that it is checked only in Windows but i think it works perfect on other Operating Systems [Linux,MacOs,Solaris] :).
I had 2 .jar files in the same directory . I wanted from the one .jar file to start the other .jar file which is in the same directory.
The problem is that when you start it from the cmd the current directory is system32.
Warnings!
The below seems to work pretty well in all the test i have done even
with folder name ;][[;'57f2g34g87-8+9-09!2##!$%^^&() or ()%&$%^##
it works well.
I am using the ProcessBuilder with the below as following:
🍂..
//The class from which i called this was the class `Main`
String path = getBasePathForClass(Main.class);
String applicationPath= new File(path + "application.jar").getAbsolutePath();
System.out.println("Directory Path is : "+applicationPath);
//Your know try catch here
//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2##!$%^^&()`
ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath);
builder.redirectErrorStream(true);
Process process = builder.start();
//...code
🍂getBasePathForClass(Class<?> classs):
/**
* Returns the absolute path of the current directory in which the given
* class
* file is.
*
* #param classs
* #return The absolute path of the current directory in which the class
* file is.
* #author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]
*/
public static final String getBasePathForClass(Class<?> classs) {
// Local variables
File file;
String basePath = "";
boolean failed = false;
// Let's give a first try
try {
file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
basePath = file.getParent();
} else {
basePath = file.getPath();
}
} catch (URISyntaxException ex) {
failed = true;
Logger.getLogger(classs.getName()).log(Level.WARNING,
"Cannot firgue out base path for class with way (1): ", ex);
}
// The above failed?
if (failed) {
try {
file = new File(classs.getClassLoader().getResource("").toURI().getPath());
basePath = file.getAbsolutePath();
// the below is for testing purposes...
// starts with File.separator?
// String l = local.replaceFirst("[" + File.separator +
// "/\\\\]", "")
} catch (URISyntaxException ex) {
Logger.getLogger(classs.getName()).log(Level.WARNING,
"Cannot firgue out base path for class with way (2): ", ex);
}
}
// fix to run inside eclipse
if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
|| basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
basePath = basePath.substring(0, basePath.length() - 4);
}
// fix to run inside netbeans
if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
basePath = basePath.substring(0, basePath.length() - 14);
}
// end fix
if (!basePath.endsWith(File.separator)) {
basePath = basePath + File.separator;
}
return basePath;
}
This code worked for me:
private static String getJarPath() throws IOException, URISyntaxException {
File f = new File(LicensingApp.class.getProtectionDomain().().getLocation().toURI());
String jarPath = f.getCanonicalPath().toString();
String jarDir = jarPath.substring( 0, jarPath.lastIndexOf( File.separator ));
return jarDir;
}
The getProtectionDomain approach might not work sometimes e.g. when you have to find the jar for some of the core java classes (e.g in my case StringBuilder class within IBM JDK), however following works seamlessly:
public static void main(String[] args) {
System.out.println(findSource(MyClass.class));
// OR
System.out.println(findSource(String.class));
}
public static String findSource(Class<?> clazz) {
String resourceToSearch = '/' + clazz.getName().replace(".", "/") + ".class";
java.net.URL location = clazz.getResource(resourceToSearch);
String sourcePath = location.getPath();
// Optional, Remove junk
return sourcePath.replace("file:", "").replace("!" + resourceToSearch, "");
}
I have another way to get the String location of a class.
URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();
The output String will have the form of
C:\Users\Administrator\new Workspace\...
The spaces and other characters are handled, and in the form without file:/. So will be easier to use.
I'm working with some code and I want it to behave differently depending on the folder name that the file is in. I don't need the absolute path just the final folder. Everything that I have seen so far is using a absolute path that is specified in the file.
This is what you want:
public static String getParentName(File file) {
if(file == null || file.isDirectory()) {
return null;
}
String parent = file.getParent();
parent = parent.substring(parent.lastIndexOf("\\") + 1, parent.length());
return parent;
}
Unfortunately there is no pre-provided method that just returns the name of the last folder in the file's path, so you have to do some String manipulation to get it.
I think java.io.File.getParent() is what you are looking for:
import java.io.File;
public class Demo {
public static void main(String[] args) {
File f = null;
String parent="not found";
f = new File("/tmp/test.txt");
parent = f.getParent();
System.out.print("parent name: "+v);
}
}
Try java.io.File.getParentFile() method.
String getFileParentName(File file) {
if (file != null && file.getParentFile() != null) {
return file.getParentFile().getName();
}
return null; // no parent for file
}
There's
String File.getParent()
There's also
File File.getParentFile()
I don't know what the return in terms of being absolute or relative, but if it's absolute you can always find the last (or second to last, depending) instance of the "\" character (remember to escape it like this "\\") to denote where the lowest folder level is.
For example, if the function returned:
"C:\Users\YourName" is where you'd get the last occurance of "\", and all characters after it would be the folder you want
"C:\Users\YourName\" is where you'd get the second to last occurance of "\", and all characters between that and the last "\" would be the folder you're looking for.
Java File API:
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
String path = "/abc/def"; // path to the directory
try
{
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles)
{
if(file.isDirectory())
{
switch(file.getName)
{
case "folder1" : //do something
break
case "folder2" : //do something else
break
}
}
}
}
catch(Exception e)
{
System.out.println("Directory not Found");
}
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.
So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
Replace "MyClass" with the name of your class.
Obviously, this will do odd things if your class was loaded from a non-file location.
Best solution for me:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
This should solve the problem with spaces and special characters.
To obtain the File for a given Class, there are two steps:
Convert the Class to a URL
Convert the URL to a File
It is important to understand both steps, and not conflate them.
Once you have the File, you can call getParentFile to get the containing folder, if that is what you need.
Step 1: Class to URL
As discussed in other answers, there are two major ways to find a URL relevant to a Class.
URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation();
URL url = Bar.class.getResource(Bar.class.getSimpleName() + ".class");
Both have pros and cons.
The getProtectionDomain approach yields the base location of the class (e.g., the containing JAR file). However, it is possible that the Java runtime's security policy will throw SecurityException when calling getProtectionDomain(), so if your application needs to run in a variety of environments, it is best to test in all of them.
The getResource approach yields the full URL resource path of the class, from which you will need to perform additional string manipulation. It may be a file: path, but it could also be jar:file: or even something nastier like bundleresource://346.fwk2106232034:4/foo/Bar.class when executing within an OSGi framework. Conversely, the getProtectionDomain approach correctly yields a file: URL even from within OSGi.
Note that both getResource("") and getResource(".") failed in my tests, when the class resided within a JAR file; both invocations returned null. So I recommend the #2 invocation shown above instead, as it seems safer.
Step 2: URL to File
Either way, once you have a URL, the next step is convert to a File. This is its own challenge; see Kohsuke Kawaguchi's blog post about it for full details, but in short, you can use new File(url.toURI()) as long as the URL is completely well-formed.
Lastly, I would highly discourage using URLDecoder. Some characters of the URL, : and / in particular, are not valid URL-encoded characters. From the URLDecoder Javadoc:
It is assumed that all characters in the encoded string are one of the following: "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "*". The character "%" is allowed but is interpreted as the start of a special escaped sequence.
...
There are two possible ways in which this decoder could deal with illegal strings. It could either leave illegal characters alone or it could throw an IllegalArgumentException. Which approach the decoder takes is left to the implementation.
In practice, URLDecoder generally does not throw IllegalArgumentException as threatened above. And if your file path has spaces encoded as %20, this approach may appear to work. However, if your file path has other non-alphameric characters such as + you will have problems with URLDecoder mangling your file path.
Working code
To achieve these steps, you might have methods like the following:
/**
* Gets the base location of the given class.
* <p>
* If the class is directly on the file system (e.g.,
* "/path/to/my/package/MyClass.class") then it will return the base directory
* (e.g., "file:/path/to").
* </p>
* <p>
* If the class is within a JAR file (e.g.,
* "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
* path to the JAR (e.g., "file:/path/to/my-jar.jar").
* </p>
*
* #param c The class whose location is desired.
* #see FileUtils#urlToFile(URL) to convert the result to a {#link File}.
*/
public static URL getLocation(final Class<?> c) {
if (c == null) return null; // could not load the class
// try the easy way first
try {
final URL codeSourceLocation =
c.getProtectionDomain().getCodeSource().getLocation();
if (codeSourceLocation != null) return codeSourceLocation;
}
catch (final SecurityException e) {
// NB: Cannot access protection domain.
}
catch (final NullPointerException e) {
// NB: Protection domain or code source is null.
}
// NB: The easy way failed, so we try the hard way. We ask for the class
// itself as a resource, then strip the class's path from the URL string,
// leaving the base path.
// get the class's raw resource path
final URL classResource = c.getResource(c.getSimpleName() + ".class");
if (classResource == null) return null; // cannot find class resource
final String url = classResource.toString();
final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
if (!url.endsWith(suffix)) return null; // weird URL
// strip the class's path from the URL string
final String base = url.substring(0, url.length() - suffix.length());
String path = base;
// remove the "jar:" prefix and "!/" suffix, if present
if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);
try {
return new URL(path);
}
catch (final MalformedURLException e) {
e.printStackTrace();
return null;
}
}
/**
* Converts the given {#link URL} to its corresponding {#link File}.
* <p>
* This method is similar to calling {#code new File(url.toURI())} except that
* it also handles "jar:file:" URLs, returning the path to the JAR file.
* </p>
*
* #param url The URL to convert.
* #return A file path suitable for use with e.g. {#link FileInputStream}
* #throws IllegalArgumentException if the URL does not correspond to a file.
*/
public static File urlToFile(final URL url) {
return url == null ? null : urlToFile(url.toString());
}
/**
* Converts the given URL string to its corresponding {#link File}.
*
* #param url The URL to convert.
* #return A file path suitable for use with e.g. {#link FileInputStream}
* #throws IllegalArgumentException if the URL does not correspond to a file.
*/
public static File urlToFile(final String url) {
String path = url;
if (path.startsWith("jar:")) {
// remove "jar:" prefix and "!/" suffix
final int index = path.indexOf("!/");
path = path.substring(4, index);
}
try {
if (PlatformUtils.isWindows() && path.matches("file:[A-Za-z]:.*")) {
path = "file:/" + path.substring(5);
}
return new File(new URL(path).toURI());
}
catch (final MalformedURLException e) {
// NB: URL is not completely well-formed.
}
catch (final URISyntaxException e) {
// NB: URL is not completely well-formed.
}
if (path.startsWith("file:")) {
// pass through the URL as-is, minus "file:" prefix
path = path.substring(5);
return new File(path);
}
throw new IllegalArgumentException("Invalid URL: " + url);
}
You can find these methods in the SciJava Common library:
org.scijava.util.ClassUtils
org.scijava.util.FileUtils.
You can also use:
CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
Use ClassLoader.getResource() to find the URL for your current class.
For example:
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
(This example taken from a similar question.)
To find the directory, you'd then need to take apart the URL manually. See the JarClassLoader tutorial for the format of a jar URL.
I'm surprised to see that none recently proposed to use Path. Here follows a citation: "The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path"
Thus, a good alternative is to get the Path objest as:
Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());
The only solution that works for me on Linux, Mac and Windows:
public static String getJarContainingFolder(Class aclass) throws Exception {
CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
File jarFile;
if (codeSource.getLocation() != null) {
jarFile = new File(codeSource.getLocation().toURI());
}
else {
String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
jarFile = new File(jarFilePath);
}
return jarFile.getParentFile().getAbsolutePath();
}
If you are really looking for a simple way to get the folder in which your JAR is located you should use this implementation.
Solutions like this are hard to find and many solutions are no longer supported, many others provide the path of the file instead of the actual directory. This is easier than other solutions you are going to find and works for java version 1.12.
new File(".").getCanonicalPath()
Gathering the Input from other answers this is a simple one too:
String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\";
Both will return a String with this format:
"C:\Users\User\Desktop\Folder\"
In a simple and concise line.
I had the the same problem and I solved it that way:
File currentJavaJarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
String currentRootDirectoryPath = currentJavaJarFilePath.replace(currentJavaJarFile.getName(), "");
I hope I was of help to you.
Here's upgrade to other comments, that seem to me incomplete for the specifics of
using a relative "folder" outside .jar file (in the jar's same
location):
String path =
YourMainClassName.class.getProtectionDomain().
getCodeSource().getLocation().getPath();
path =
URLDecoder.decode(
path,
"UTF-8");
BufferedImage img =
ImageIO.read(
new File((
new File(path).getParentFile().getPath()) +
File.separator +
"folder" +
File.separator +
"yourfile.jpg"));
For getting the path of running jar file I have studied the above solutions and tried all methods which exist some difference each other. If these code are running in Eclipse IDE they all should be able to find the path of the file including the indicated class and open or create an indicated file with the found path.
But it is tricky, when run the runnable jar file directly or through the command line, it will be failed as the path of jar file gotten from the above methods will give an internal path in the jar file, that is it always gives a path as
rsrc:project-name (maybe I should say that it is the package name of the main class file - the indicated class)
I can not convert the rsrc:... path to an external path, that is when run the jar file outside the Eclipse IDE it can not get the path of jar file.
The only possible way for getting the path of running jar file outside Eclipse IDE is
System.getProperty("java.class.path")
this code line may return the living path (including the file name) of the running jar file (note that the return path is not the working directory), as the java document and some people said that it will return the paths of all class files in the same directory, but as my tests if in the same directory include many jar files, it only return the path of running jar (about the multiple paths issue indeed it happened in the Eclipse).
Other answers seem to point to the code source which is Jar file location which is not a directory.
Use
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
the selected answer above is not working if you run your jar by click on it from Gnome desktop environment (not from any script or terminal).
Instead, I have fond that the following solution is working everywhere:
try {
return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
I had to mess around a lot before I finally found a working (and short) solution.
It is possible that the jarLocation comes with a prefix like file:\ or jar:file\, which can be removed by using String#substring().
URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();
For the jar file path:
String jarPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
For getting the directory path of that jar file:
String dirPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getParent();
The results of the two lines above are like this:
/home/user/MyPrograms/myapp/myjar.jar (value of jarPath)
/home/user/MyPrograms/myapp (value of dirPath)
public static String dir() throws URISyntaxException
{
URI path=Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
String name= Main.class.getPackage().getName()+".jar";
String path2 = path.getRawPath();
path2=path2.substring(1);
if (path2.contains(".jar"))
{
path2=path2.replace(name, "");
}
return path2;}
Works good on Windows
I tried to get the jar running path using
String folder = MyClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();
c:\app>java -jar application.jar
Running the jar application named "application.jar", on Windows in the folder "c:\app", the value of the String variable "folder" was "\c:\app\application.jar" and I had problems testing for path's correctness
File test = new File(folder);
if(file.isDirectory() && file.canRead()) { //always false }
So I tried to define "test" as:
String fold= new File(folder).getParentFile().getPath()
File test = new File(fold);
to get path in a right format like "c:\app" instead of "\c:\app\application.jar" and I noticed that it work.
The simplest solution is to pass the path as an argument when running the jar.
You can automate this with a shell script (.bat in Windows, .sh anywhere else):
java -jar my-jar.jar .
I used . to pass the current working directory.
UPDATE
You may want to stick the jar file in a sub-directory so users don't accidentally click it. Your code should also check to make sure that the command line arguments have been supplied, and provide a good error message if the arguments are missing.
Actually here is a better version - the old one failed if a folder name had a space in it.
private String getJarFolder() {
// get name and path
String name = getClass().getName().replace('.', '/');
name = getClass().getResource("/" + name + ".class").toString();
// remove junk
name = name.substring(0, name.indexOf(".jar"));
name = name.substring(name.lastIndexOf(':')-1, name.lastIndexOf('/')+1).replace('%', ' ');
// remove escape characters
String s = "";
for (int k=0; k<name.length(); k++) {
s += name.charAt(k);
if (name.charAt(k) == ' ') k += 2;
}
// replace '/' with system separator char
return s.replace('/', File.separatorChar);
}
As for failing with applets, you wouldn't usually have access to local files anyway. I don't know much about JWS but to handle local files might it not be possible to download the app.?
String path = getClass().getResource("").getPath();
The path always refers to the resource within the jar file.
Try this:
String path = new File("").getAbsolutePath();
This code worked for me to identify if the program is being executed inside a JAR file or IDE:
private static boolean isRunningOverJar() {
try {
String pathJar = Application.class.getResource(Application.class.getSimpleName() + ".class").getFile();
if (pathJar.toLowerCase().contains(".jar")) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
If I need to get the Windows full path of JAR file I am using this method:
private static String getPathJar() {
try {
final URI jarUriPath =
Application.class.getResource(Application.class.getSimpleName() + ".class").toURI();
String jarStringPath = jarUriPath.toString().replace("jar:", "");
String jarCleanPath = Paths.get(new URI(jarStringPath)).toString();
if (jarCleanPath.toLowerCase().contains(".jar")) {
return jarCleanPath.substring(0, jarCleanPath.lastIndexOf(".jar") + 4);
} else {
return null;
}
} catch (Exception e) {
log.error("Error getting JAR path.", e);
return null;
}
}
My complete code working with a Spring Boot application using CommandLineRunner implementation, to ensure that the application always be executed within of a console view (Double clicks by mistake in JAR file name), I am using the next code:
#SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) throws IOException {
Console console = System.console();
if (console == null && !GraphicsEnvironment.isHeadless() && isRunningOverJar()) {
Runtime.getRuntime().exec(new String[]{"cmd", "/c", "start", "cmd", "/k",
"java -jar \"" + getPathJar() + "\""});
} else {
SpringApplication.run(Application.class, args);
}
}
#Override
public void run(String... args) {
/*
Additional code here...
*/
}
private static boolean isRunningOverJar() {
try {
String pathJar = Application.class.getResource(Application.class.getSimpleName() + ".class").getFile();
if (pathJar.toLowerCase().contains(".jar")) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
private static String getPathJar() {
try {
final URI jarUriPath =
Application.class.getResource(Application.class.getSimpleName() + ".class").toURI();
String jarStringPath = jarUriPath.toString().replace("jar:", "");
String jarCleanPath = Paths.get(new URI(jarStringPath)).toString();
if (jarCleanPath.toLowerCase().contains(".jar")) {
return jarCleanPath.substring(0, jarCleanPath.lastIndexOf(".jar") + 4);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
}
Something that is frustrating is that when you are developing in Eclipse MyClass.class.getProtectionDomain().getCodeSource().getLocation() returns the /bin directory which is great, but when you compile it to a jar, the path includes the /myjarname.jar part which gives you illegal file names.
To have the code work both in the ide and once it is compiled to a jar, I use the following piece of code:
URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
myFile = new File(applicationRootPath, "filename");
}
else{
myFile = new File(applicationRootPath.getParentFile(), "filename");
}
Not really sure about the others but in my case it didn't work with a "Runnable jar" and i got it working by fixing codes together from phchen2 answer and another from this link :How to get the path of a running JAR file?
The code:
String path=new java.io.File(Server.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getAbsolutePath();
path=path.substring(0, path.lastIndexOf("."));
path=path+System.getProperty("java.class.path");
Have tried several of the solutions up there but none yielded correct results for the (probably special) case that the runnable jar has been exported with "Packaging external libraries" in Eclipse. For some reason all solutions based on the ProtectionDomain do result in null in that case.
From combining some solutions above I managed to achieve the following working code:
String surroundingJar = null;
// gets the path to the jar file if it exists; or the "bin" directory if calling from Eclipse
String jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath()).getAbsolutePath();
// gets the "bin" directory if calling from eclipse or the name of the .jar file alone (without its path)
String jarFileFromSys = System.getProperty("java.class.path").split(";")[0];
// If both are equal that means it is running from an IDE like Eclipse
if (jarFileFromSys.equals(jarDir))
{
System.out.println("RUNNING FROM IDE!");
// The path to the jar is the "bin" directory in that case because there is no actual .jar file.
surroundingJar = jarDir;
}
else
{
// Combining the path and the name of the .jar file to achieve the final result
surroundingJar = jarDir + jarFileFromSys.substring(1);
}
System.out.println("JAR File: " + surroundingJar);
The above methods didn't work for me in my Spring environment, since Spring shades the actual classes into a package called BOOT-INF, thus not the actual location of the running file. I found another way to retrieve the running file through the Permissions object which have been granted to the running file:
public static Path getEnclosingDirectory() {
return Paths.get(FileUtils.class.getProtectionDomain().getPermissions()
.elements().nextElement().getName()).getParent();
}
Mention that it is checked only in Windows but i think it works perfect on other Operating Systems [Linux,MacOs,Solaris] :).
I had 2 .jar files in the same directory . I wanted from the one .jar file to start the other .jar file which is in the same directory.
The problem is that when you start it from the cmd the current directory is system32.
Warnings!
The below seems to work pretty well in all the test i have done even
with folder name ;][[;'57f2g34g87-8+9-09!2##!$%^^&() or ()%&$%^##
it works well.
I am using the ProcessBuilder with the below as following:
🍂..
//The class from which i called this was the class `Main`
String path = getBasePathForClass(Main.class);
String applicationPath= new File(path + "application.jar").getAbsolutePath();
System.out.println("Directory Path is : "+applicationPath);
//Your know try catch here
//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2##!$%^^&()`
ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath);
builder.redirectErrorStream(true);
Process process = builder.start();
//...code
🍂getBasePathForClass(Class<?> classs):
/**
* Returns the absolute path of the current directory in which the given
* class
* file is.
*
* #param classs
* #return The absolute path of the current directory in which the class
* file is.
* #author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]
*/
public static final String getBasePathForClass(Class<?> classs) {
// Local variables
File file;
String basePath = "";
boolean failed = false;
// Let's give a first try
try {
file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
basePath = file.getParent();
} else {
basePath = file.getPath();
}
} catch (URISyntaxException ex) {
failed = true;
Logger.getLogger(classs.getName()).log(Level.WARNING,
"Cannot firgue out base path for class with way (1): ", ex);
}
// The above failed?
if (failed) {
try {
file = new File(classs.getClassLoader().getResource("").toURI().getPath());
basePath = file.getAbsolutePath();
// the below is for testing purposes...
// starts with File.separator?
// String l = local.replaceFirst("[" + File.separator +
// "/\\\\]", "")
} catch (URISyntaxException ex) {
Logger.getLogger(classs.getName()).log(Level.WARNING,
"Cannot firgue out base path for class with way (2): ", ex);
}
}
// fix to run inside eclipse
if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
|| basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
basePath = basePath.substring(0, basePath.length() - 4);
}
// fix to run inside netbeans
if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
basePath = basePath.substring(0, basePath.length() - 14);
}
// end fix
if (!basePath.endsWith(File.separator)) {
basePath = basePath + File.separator;
}
return basePath;
}
This code worked for me:
private static String getJarPath() throws IOException, URISyntaxException {
File f = new File(LicensingApp.class.getProtectionDomain().().getLocation().toURI());
String jarPath = f.getCanonicalPath().toString();
String jarDir = jarPath.substring( 0, jarPath.lastIndexOf( File.separator ));
return jarDir;
}
The getProtectionDomain approach might not work sometimes e.g. when you have to find the jar for some of the core java classes (e.g in my case StringBuilder class within IBM JDK), however following works seamlessly:
public static void main(String[] args) {
System.out.println(findSource(MyClass.class));
// OR
System.out.println(findSource(String.class));
}
public static String findSource(Class<?> clazz) {
String resourceToSearch = '/' + clazz.getName().replace(".", "/") + ".class";
java.net.URL location = clazz.getResource(resourceToSearch);
String sourcePath = location.getPath();
// Optional, Remove junk
return sourcePath.replace("file:", "").replace("!" + resourceToSearch, "");
}
I have another way to get the String location of a class.
URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();
The output String will have the form of
C:\Users\Administrator\new Workspace\...
The spaces and other characters are handled, and in the form without file:/. So will be easier to use.
I am not in front of an IDE right now, just looking at the API specs.
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL jar = src.getLocation();
}
I want to determine which JAR file a class is from. Is this the way to do it?
Yes. It works for all classes except classes loaded by bootstrap classloader. The other way to determine is:
Class klass = String.class;
URL location = klass.getResource('/' + klass.getName().replace('.', '/') + ".class");
As notnoop pointed out klass.getResource() method returns the location of the class file itself. For example:
jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class
file:/projects/classes/pkg/MyClass$1.class
The getProtectionDomain().getCodeSource().getLocation() method returns the location of the jar file or CLASSPATH
file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar
file:/projects/classes
Checkout the LiveInjector.findPathJar() from Lombok Patcher LiveInjector.java. Note that it special cases where the file doesn't actually live in a jar, and you might want to change that.
/**
* If the provided class has been loaded from a jar file that is on the local file system, will find the absolute path to that jar file.
*
* #param context The jar file that contained the class file that represents this class will be found. Specify {#code null} to let {#code LiveInjector}
* find its own jar.
* #throws IllegalStateException If the specified class was loaded from a directory or in some other way (such as via HTTP, from a database, or some
* other custom classloading device).
*/
public static String findPathJar(Class<?> context) throws IllegalStateException {
if (context == null) context = LiveInjector.class;
String rawName = context.getName();
String classFileName;
/* rawName is something like package.name.ContainingClass$ClassName. We need to turn this into ContainingClass$ClassName.class. */ {
int idx = rawName.lastIndexOf('.');
classFileName = (idx == -1 ? rawName : rawName.substring(idx+1)) + ".class";
}
String uri = context.getResource(classFileName).toString();
if (uri.startsWith("file:")) throw new IllegalStateException("This class has been loaded from a directory and not from a jar file.");
if (!uri.startsWith("jar:file:")) {
int idx = uri.indexOf(':');
String protocol = idx == -1 ? "(unknown)" : uri.substring(0, idx);
throw new IllegalStateException("This class has been loaded remotely via the " + protocol +
" protocol. Only loading from a jar on the local file system is supported.");
}
int idx = uri.indexOf('!');
//As far as I know, the if statement below can't ever trigger, so it's more of a sanity check thing.
if (idx == -1) throw new IllegalStateException("You appear to have loaded this class from a local jar file, but I can't make sense of the URL!");
try {
String fileName = URLDecoder.decode(uri.substring("jar:file:".length(), idx), Charset.defaultCharset().name());
return new File(fileName).getAbsolutePath();
} catch (UnsupportedEncodingException e) {
throw new InternalError("default charset doesn't exist. Your VM is borked.");
}
}
Use
String path = <Any of your class within the jar>.class.getProtectionDomain().getCodeSource().getLocation().getPath();
If this contains multiple entries then do some substring operation.
private String resourceLookup(String lookupResourceName) {
try {
if (lookupResourceName == null || lookupResourceName.length()==0) {
return "";
}
// "/java/lang/String.class"
// Check if entered data was in java class name format
if (lookupResourceName.indexOf("/")==-1) {
lookupResourceName = lookupResourceName.replaceAll("[.]", "/");
lookupResourceName = "/" + lookupResourceName + ".class";
}
URL url = this.getClass().getResource(lookupResourceName);
if (url == null) {
return("Unable to locate resource "+ lookupResourceName);
}
String resourceUrl = url.toExternalForm();
Pattern pattern =
Pattern.compile("(zip:|jar:file:/)(.*)!/(.*)", Pattern.CASE_INSENSITIVE);
String jarFilename = null;
String resourceFilename = null;
Matcher m = pattern.matcher(resourceUrl);
if (m.find()) {
jarFilename = m.group(2);
resourceFilename = m.group(3);
} else {
return "Unable to parse URL: "+ resourceUrl;
}
if (!jarFilename.startsWith("C:") ){
jarFilename = "/"+jarFilename; // make absolute path on Linux
}
File file = new File(jarFilename);
Long jarSize=null;
Date jarDate=null;
Long resourceSize=null;
Date resourceDate=null;
if (file.exists() && file.isFile()) {
jarSize = file.length();
jarDate = new Date(file.lastModified());
try {
JarFile jarFile = new JarFile(file, false);
ZipEntry entry = jarFile.getEntry(resourceFilename);
resourceSize = entry.getSize();
resourceDate = new Date(entry.getTime());
} catch (Throwable e) {
return ("Unable to open JAR" + jarFilename + " "+resourceUrl +"\n"+e.getMessage());
}
return "\nresource: "+resourceFilename+"\njar: "+jarFilename + " \nJarSize: " +jarSize+" \nJarDate: " +jarDate.toString()+" \nresourceSize: " +resourceSize+" \nresourceDate: " +resourceDate.toString()+"\n";
} else {
return("Unable to load jar:" + jarFilename+ " \nUrl: " +resourceUrl);
}
} catch (Exception e){
return e.getMessage();
}
}
With Linux, I'm using a small script to help me find in which jar a class lies that can be used in a find -exec:
findclass.sh:
unzip -l "$1" 2>/dev/null | grep $2 >/dev/null 2>&1 && echo "$1"
Basically, as jars are zip, unzip -l will print the list of class resources, so you'll have to convert . to /. You could perform the replacement in the script with a tr, but it's not too much trouble to do it yourself when calling the script.
The, the idea is to use find on the root of your classpath to locate all jars, then runs findclass.sh on all found jars to look for a match.
It doesn't handle multi-directories, but if you carefully choose the root you can get it to work.
Now, find which jar contains class org.apache.commons.lang3.RandomUtils to you un-mavenize your project (...):
$ find ~/.m2/repository/ -type f -name '*.jar' -exec findclass.sh {} org/apache/commons/lang3/RandomUtils \;
.m2/repository/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar
.m2/repository/org/apache/commons/commons-lang3/3.6/commons-lang3-3.6.jar
.m2/repository/org/apache/commons/commons-lang3/3.6/commons-lang3-3.6-sources.jar
$