Let's say I have my main class in C:\Users\Justian\Documents\
. How can I get my program to show that it's in C:\Users\Justian\Documents
?
Hard-Coding is not an option- it needs to be adaptable if it's moved to another location.
I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.
This question is related to
java
path
working-directory
If you want to get your current working directory then use the following line
System.out.println(new File("").getAbsolutePath());
this.getClass().getClassLoader().getResource("").getPath()
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());
}
}
Update as per the comment of the OP:
I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.
That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()
File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
@Override public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
Or to pass its path as main()
argument.
Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.
So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.
I just used:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
If you want the absolute path of the current source code, my suggestion is:
String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));
File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());
Prints something like:
/path/to/current/directory
/path/to/current/directory/.
Note that File.getCanonicalPath()
throws a checked IOException but it will remove things like ../../../
Source: Stackoverflow.com