Java path of running jar

How to get the real path of Java application at runtime?

I am creating a Java application where I am using log4j. I have given the absolute path of configuration log4j file and also an absolute path of generated log file(where this log file are generated). I can get the absolute path of a Java web application at run time via:

String prefix = getServletContext().getRealPath("/"); 

15 Answers 15

String path = new File(".").getCanonicalPath(); 

Does this really return the directory where the application is installed? It looks like it should return the working directory, which is not necessarily the same thing.

It isn’t clear what you’re asking for. I don’t know what ‘with respect to the web application we are using’ means if getServletContext().getRealPath() isn’t the answer, but:

  • The current user’s current working directory is given by System.getProperty(«user.dir»)
  • The current user’s home directory is given by System.getProperty(«user.home»)
  • The location of the JAR file from which the current class was loaded is given by this.getClass().getProtectionDomain().getCodeSource().getLocation() .

@Gary Did you look at the documentation before posting that? It is the current working directory. user.home is the user’s home directory.

I am upvoting this. I didn’t get solution of my problem from this post, but this code was what i need for my project. (getting path of running java application and add the path to java.path -my dll is always in this path-) Thanks.

Читайте также:  Python first char uppercase

And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation() ?

Since the application path of a JAR and an application running from inside an IDE differs, I wrote the following code to consistently return the correct current directory:

import java.io.File; import java.net.URISyntaxException; public class ProgramDirectoryUtilities < private static String getJarName() < return new File(ProgramDirectoryUtilities.class.getProtectionDomain() .getCodeSource() .getLocation() .getPath()) .getName(); >private static boolean runningFromJAR() < String jarName = getJarName(); return jarName.contains(".jar"); >public static String getProgramDirectory() < if (runningFromJAR()) < return getCurrentJARDirectory(); >else < return getCurrentProjectDirectory(); >> private static String getCurrentProjectDirectory() < return new File("").getAbsolutePath(); >private static String getCurrentJARDirectory() < try < return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent(); >catch (URISyntaxException exception) < exception.printStackTrace(); >return null; > > 

Simply call getProgramDirectory() and you should be good either way.

I know it’s old, but I’m still getting different results between running the app and running the unit test, both from within IDE. Any idea?

If you’re talking about a web application, you should use the getRealPath from a ServletContext object.

public class MyServlet extends Servlet < public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException< String webAppPath = getServletContext().getRealPath("/"); >> 

I use this method to get complete path to jar or exe.

File pto = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI()); pto.getAbsolutePath()); 

Return the working directory and not the application directory. So, when press enter on a file to open with the application, we take wrong application path.

It is better to save files into a sub-directory of user.home than wherever the app. might reside.

Sun went to considerable effort to ensure that applets and apps. launched using Java Web Start cannot determine the apps. real path. This change broke many apps. I would not be surprised if the changes are extended to other apps.

/***************************************************************************** * return application path * @return *****************************************************************************/ public static String getApplcatonPath() < CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource(); File rootPath = null; try < rootPath = new File(codeSource.getLocation().toURI().getPath()); >catch (URISyntaxException e) < // TODO Auto-generated catch block e.printStackTrace(); >return rootPath.getParentFile().getPath(); >//end of getApplcatonPath() 

Of cours it will throw an NPE. rootPath is null and never changes in the exception case, and then you dereference it. If you want to debate, provide facts or arguments. Not just denial.

If you want to get the real path of java web application such as Spring (Servlet), you can get it from Servlet Context object that comes with your HttpServletRequest.

@GetMapping("/") public String index(ModelMap m, HttpServletRequest request) < String realPath = request.getServletContext().getRealPath("/"); System.out.println(realPath); return "index"; >

I think everyone’s missing a key problem with this.

String prefix = getServletContext().getRealPath("/"); 

The servlet instance could be on one of the arbitrarily many nodes and doesn’t technically require a file system at all.

In Java EE containers for example the application could be loaded from a database or even a directory server. Different parts of the application can also be running on different nodes. Access to the world outside the application is provided by the application server.

Use java.util.logging or Apache Commons Logging if you have to maintain compatibility with legacy log4j. Tell the application server where the log file is supposed to go.

Источник

Get location of JAR file

So basicly I want the path of the JAR file without the filename and not the ClassPath. Any way of doing this?

The specification is incomplete. What should be done if you’re not running from a JAR? What if the JAR lives in some Network?

Well the thing is that i’m trying to create a directory containing files and that has to be on my desktop or wherever i’m running the JAR from. If I run it in debug mode within Eclipse it does create files in the bin/server folder.

4 Answers 4

Since it doesn’t work in certain test-cases, I’ll update the answer.

The correct way to do this should be with ClassLoader :

File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath()); System.out.println(jarDir.getAbsolutePath()); 

Tested on various classpaths, the output was correct.

File f = new File(System.getProperty("java.class.path")); File dir = f.getAbsoluteFile().getParentFile(); String path = dir.toString(); 

It works for me, my program is in:

C:\Users\User01\Documents\app1\dist\JavaApplication1.jar 
C:\Users\User01\Documents\app1\dist 

@dbw The classpath can be a list of jar files, zip files and directories, separated by ‘:’ in Unix or ‘;’ in Windows. Clearly new File(«foo.jar:bar/:baz.jar») wouldn’t work then.

Herewith my version of computing the jar directory

/** * Compute the absolute file path to the jar file. * The framework is based on http://stackoverflow.com/a/12733172/1614775 * But that gets it right for only one of the four cases. * * @param aclass A class residing in the required jar. * * @return A File object for the directory in which the jar file resides. * During testing with NetBeans, the result is ./build/classes/, * which is the directory containing what will be in the jar. */ public static File getJarDir(Class aclass) < URL url; String extURL; // url.toExternalForm(); // get an url try < url = aclass.getProtectionDomain().getCodeSource().getLocation(); // url is in one of two forms // ./build/classes/ NetBeans test // jardir/JarName.jar froma jar >catch (SecurityException ex) < url = aclass.getResource(aclass.getSimpleName() + ".class"); // url is in one of two forms, both ending "/com/physpics/tools/ui/PropNode.class" // file:/U:/Fred/java/Tools/UI/build/classes // jar:file:/U:/Fred/java/Tools/UI/dist/UI.jar! >// convert to external form extURL = url.toExternalForm(); // prune for various cases if (extURL.endsWith(".jar")) // from getCodeSource extURL = extURL.substring(0, extURL.lastIndexOf("/")); else < // from getResource String suffix = "/"+(aclass.getName()).replace(".", "/")+".class"; extURL = extURL.replace(suffix, ""); if (extURL.startsWith("jar:") && extURL.endsWith(".jar!")) extURL = extURL.substring(4, extURL.lastIndexOf("/")); >// convert back to url try < url = new URL(extURL); >catch (MalformedURLException mux) < // leave url unchanged; probably does not happen >// convert url to File try < return new File(url.toURI()); >catch(URISyntaxException ex) < return new File(url.getPath()); >> 

Источник

How do I get the directory that the currently executing jar file is in? [duplicate]

I’m running a jar file in various locations and I’m trying to figure out how to get the location of the jar file that is running.

5 Answers 5

Not a perfect solution but this will return class code base’s location:

getClass().getProtectionDomain().getCodeSource().getLocation() 

Not perfect? This is actually the most reliable since the other proposed suggestions returns the current working directory which is not per se the folder where the JAR is located. E.g. if you do cd /somefolder and then java -jar /otherfolder/file.jar then other suggestions would return /somefolder . +1.

It isn’t always possible to determine the location of the enclosing JAR (class loaders can use anything for storage, not just a file system), but when it is, this is the way to do it.

As noted in the comments, this is not a direct answer to the question, but may actually be what many people are looking for (the current directory of the executing code):

As @Will Hartung said, «The current directory may well have nothing to do with where the executing jar is located.»

Here is my method to get execution path from anywhere

private static String GetExecutionPath() < String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("/")); absolutePath = absolutePath.replaceAll("%20"," "); // Surely need to do this here return absolutePath; >

Consider the following function

 //This method will work on Windows and Linux as well. public String getPath()

This seems like an iffy question to start out with.

If I am running code in Java, it is running out of rt.jar and probably a dozen other jars.

The very first files to run will actually be in rt.jar, rt.jar it calls your main.

If you write a class that allows you to tell what jar you are running and that class gets moved into a different jar, then you are not «running out of» the jar that contained your main any more.

I think what you want is the command line that started your application, but if you CD’d to the directory first, then it might not have the full path to your jar.

Also, you may not be running from a jar—someone could have expanded your jar into classes in a directory and is running it that way.

Personally I’d just wrap your program in a shell script launcher where you could look at your current location and the location of the jar file and then pass them into java.

Источник

Get name of running Jar or Exe

What I need to do is get the name of the running jar/exe file (it would be an EXE on windows, jar on mac/linux). I have been searching around and I can’t seem to find out how. How to get name of running Jar or Exe?

5 Answers 5

Hope this can help you, I test the code and this return you the full path and the name.

Maybe you want to play a little more with the code and give me some feed back.

File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());‌ 

This was found on a similar but not == question on stackoverflow How to get the path of a running JAR file?

«give me some feed back.» Fails for applets and anything launched using JWS. Usually a bad strategy to implement a good idea. Until the OP mentions what the idea is, we are guessing about the best way to help.

Hi I managed to use this approach to get the path, but it’s in .target/classes folder, but I want to read the Manifest file in another folder under target folder, I’m new to Java, is there any way to do this? Many thanks.

returns simple path in the compiled application and an error in jar:

private File getJarFile() throws FileNotFoundException < String path = Main.class.getResource(Main.class.getSimpleName() + ".class").getFile(); if(path.startsWith("/")) < throw new FileNotFoundException("This is not a jar file: \n" + path); >path = ClassLoader.getSystemClassLoader().getResource(path).getFile(); return new File(path.substring(0, path.lastIndexOf('!'))); > 

I’ve been trying all evening to find something that works. This saved me!! Thank you! I’m not sure why, but class.getProtectionDomain().getCodeSource().getLocation(), and everything else for that matter, was returning rsrc:. .

 File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath()); 

as for the exe, as I’m assuming you’re using some sort of wrapper, you’ll need to know the name of the exe before it’s run. Then you could use something like :

 Process p = Runtime.getRuntime().exec (System.getenv("windir") +"\\system32\\"+"tasklist.exe"); 

Источник

Оцените статью