I want to access my current working directory using java.
My code :
String current = new java.io.File( \".\" ).getCanonicalPath();
System.ou
Use CodeSource#getLocation().
This works fine in JAR files as well. You can obtain CodeSource
by ProtectionDomain#getCodeSource() and the ProtectionDomain
in turn can be obtained by Class#getProtectionDomain().
public class Test {
public static void main(String... args) throws Exception {
URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
}
}
generally, as a File object:
File getCwd() {
return new File("").getAbsoluteFile();
}
you may want to have full qualified string like "D:/a/b/c" doing:
getCwd().getAbsolutePath()
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!
;][[;'57f2g34g87-8+9-09!2#@!$%^^&()
or ()%&$%^@#
it works well.ProcessBuilder
with the below as following:
I hope you want to access the current directory including the package i.e. If your Java program is in c:\myApp\com\foo\src\service\MyTest.java
and you want to print until c:\myApp\com\foo\src\service
then you can try the following code:
String myCurrentDir = System.getProperty("user.dir")
+ File.separator
+ System.getProperty("sun.java.command")
.substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
.replace(".", File.separator);
System.out.println(myCurrentDir);
Note: This code is only tested in Windows with Oracle JRE.