Runnable jar file does not find resources - java

I have created a jar file that runs the login screen. When I enter the user's credentials, it uses an XML file to validate the credentials. My jar file does not seem to find this XML file. Here is my file directory:
My jar file is created like this:
The users.xml file is loaded like this
URL url = getClass().getResource("/users.xml");
String path = url.getPath();
String loginQuery = "for $x in doc('"+ path +"')//User where ($x/Username='" + username +"') "
+ " and ($x/Password='" + password + "') return data($x/Name)";
My project works fine on eclipse when I run it. I have no idea why my jar doesn't work

I think that's a problem with your packaging. I just compiled a test program, showing stuff works as expected:
mabi#terra ~ $ cat /tmp/test/Test.java
import java.net.URL;
public class Test {
public static void main(String[] args) {
Test instance = new Test();
URL absDynRes = instance.getClass().getResource("/users.xml");
if (absDynRes == null) {
System.out.println("Absolute dynamic URL is null");
} else {
System.out.println("Got: " + absDynRes);
}
}
}
Compile and run:
mabi#terra ~ $ cd /tmp/test/ && javac Test.java
mabi#terra /tmp/test $ jar cfe test.jar Test -C /tmp/test Test.class users.xml
mabi#terra /tmp/test $ java -jar test.jar
Got: jar:file:/tmp/test/test.jar!/users.xml
Either you don't have the file in your jar or the class returned by getClass() resides in a different jar then the one containing users.xml.

Related

java.io.FileNotFoundException: data.csv (The system cannot find the file specified) [duplicate]

I want to access my current working directory using Java.
My code:
String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + currentPath);
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" + currentDir);
Output:
Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32
My output is not correct because the C drive is not my current directory.
How to get the current directory?
Code :
public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}
This will print the absolute path of the current directory from where your application was initialized.
Explanation:
From the documentation:
java.io package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir and is the directory from where the JVM was invoked.
See: Path Operations (The Java™ Tutorials > Essential Classes > Basic I/O).
Using java.nio.file.Path and java.nio.file.Paths, you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);
This outputs:
Current absolute path is: /Users/george/NetBeansProjects/Tutorials
that in my case is where I ran the class from.
Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.
The following works on Java 7 and up (see here for documentation).
import java.nio.file.Paths;
Paths.get(".").toAbsolutePath().normalize().toString();
This will give you the path of your current working directory:
Path path = FileSystems.getDefault().getPath(".");
And this will give you the path to a file called "Foo.txt" in the working directory:
Path path = FileSystems.getDefault().getPath("Foo.txt");
Edit :
To obtain an absolute path of current directory:
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
* Update *
To get current working directory:
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
Java 11 and newer
This solution is better than others and more portable:
Path cwd = Path.of("").toAbsolutePath();
Or even
String cwd = Path.of("").toAbsolutePath().toString();
This is the solution for me
File currentDir = new File("");
What makes you think that c:\windows\system32 is not your current directory? The user.dir property is explicitly to be "User's current working directory".
To put it another way, unless you start Java from the command line, c:\windows\system32 probably is your CWD. That is, if you are double-clicking to start your program, the CWD is unlikely to be the directory that you are double clicking from.
Edit: It appears that this is only true for old windows and/or Java versions.
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());
}
}
this.getClass().getClassLoader().getResource("").getPath()
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()
I'm on Linux and get same result for both of these approaches:
#Test
public void aaa()
{
System.err.println(Paths.get("").toAbsolutePath().toString());
System.err.println(System.getProperty("user.dir"));
}
Paths.get("") docs
System.getProperty("user.dir") docs
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.
On Linux when you run a jar file from terminal, these both will return the same String: "/home/CurrentUser", no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.
Paths.get("").toAbsolutePath().toString();
System.getProperty("user.dir");
If your Class with main would be called MainClass, then try:
MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();
This will return a String with absolute path of the jar file.
Using Windows user.dir returns the directory as expected, but NOT when you start your application with elevated rights (run as admin), in that case you get C:\WINDOWS\system32
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;
}
assume that you're trying to run your project inside eclipse, or netbean or stand alone from command line. I have write a method to fix it
public static final String getBasePathForClass(Class<?> clazz) {
File file;
try {
String basePath = null;
file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
basePath = file.getParent();
} else {
basePath = file.getPath();
}
// 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 netbean
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;
} catch (URISyntaxException e) {
throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
}
}
To use, everywhere you want to get base path to read file, you can pass your anchor class to above method, result may be the thing you need :D
Best,
For Java 11 you could also use:
var path = Path.of(".").toRealPath();
This is a very confuse topic, and we need to understand some concepts before providing a real solution.
The File, and NIO File Api approaches with relative paths "" or "." uses internally the system parameter "user.dir" value to determine the return location.
The "user.dir" value is based on the USER working directory, and the behavior of that value depends on the operative system, and the way the jar is executed.
For example, executing a JAR from Linux using a File Explorer (opening it by double click) will set user.dir with the user home directory, regardless of the location of the jar. If the same jar is executed from command line, it will return the jar location, because each cd command to the jar location modified the working directory.
Having said that, the solutions using Java NIO, Files or "user.dir" property will work for all the scenarios in the way the "user.dir" has the correct value.
String userDirectory = System.getProperty("user.dir");
String userDirectory2 = new File("").getAbsolutePath();
String userDirectory3 = Paths.get("").toAbsolutePath().toString();
We could use the following code:
new File(MyApp.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI().getPath())
.getParent();
to get the current location of the executed JAR, and personally I used the following approach to get the expected location and overriding the "user.dir" system property at the very beginning of the application. So, later when the other approaches are used, I will get the expected values always.
More details here -> https://blog.adamgamboa.dev/getting-current-directory-path-in-java/
public class MyApp {
static {
//This static block runs at the very begin of the APP, even before the main method.
try{
File file = new File(MyApp.class.getProtectionDomain().getCodeSource()
.getLocation().toURI().getPath());
String basePath = file.getParent();
//Overrides the existing value of "user.dir"
System.getProperties().put("user.dir", basePath);
}catch(URISyntaxException ex){
//log the error
}
}
public static void main(String args []){
//Your app logic
//All these approaches should return the expected value
//regardless of the way the jar is executed.
String userDirectory = System.getProperty("user.dir");
String userDirectory2 = new File("").getAbsolutePath();
String userDirectory3 = Paths.get("").toAbsolutePath().toString();
}
}
I hope this explanation and details are helpful to others...
Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with -D and defining a variable to hold the info
Something like
java -D com.mycompany.workingDir="%0"
That's not quite right, but you get the idea. Then System.getProperty("com.mycompany.workingDir")...
This is my silver bullet when ever the moment of confusion bubbles in.(Call it as first thing in main). Maybe for example JVM is slipped to be different version by IDE. This static function searches current process PID and opens VisualVM on that pid. Confusion stops right there because you want it all and you get it...
public static void callJVisualVM() {
System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
//next search current jdk/jre
String jre_root = null;
String start = "vir";
try {
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
String jvmName = runtime.getName();
System.out.println("JVM Name = " + jvmName);
long pid = Long.valueOf(jvmName.split("#")[0]);
System.out.println("JVM PID = " + pid);
Runtime thisRun = Runtime.getRuntime();
jre_root = System.getProperty("java.home");
System.out.println("jre_root:" + jre_root);
start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
thisRun.exec(start);
} catch (Exception e) {
System.getProperties().list(System.out);
e.printStackTrace();
}
}
This isn't exactly what's asked, but here's an important note: When running Java on a Windows machine, the Oracle installer puts a "java.exe" into C:\Windows\system32, and this is what acts as the launcher for the Java application (UNLESS there's a java.exe earlier in the PATH, and the Java app is run from the command-line). This is why File(".") keeps returning C:\Windows\system32, and why running examples from macOS or *nix implementations keep coming back with different results from Windows.
Unfortunately, there's really no universally correct answer to this one, as far as I have found in twenty years of Java coding unless you want to create your own native launcher executable using JNI Invocation, and get the current working directory from the native launcher code when it's launched. Everything else is going to have at least some nuance that could break under certain situations.
Try something like this I know I am late for the answer but this obvious thing happened in java8 a new version from where this question is asked but..
The code
import java.io.File;
public class Find_this_dir {
public static void main(String[] args) {
//some sort of a bug in java path is correct but file dose not exist
File this_dir = new File("");
//but these both commands work too to get current dir
// File this_dir_2 = new File(this_dir.getAbsolutePath());
File this_dir_2 = new File(new File("").getAbsolutePath());
System.out.println("new File(" + "\"\"" + ")");
System.out.println(this_dir.getAbsolutePath());
System.out.println(this_dir.exists());
System.out.println("");
System.out.println("new File(" + "new File(" + "\"\"" + ").getAbsolutePath()" + ")");
System.out.println(this_dir_2.getAbsolutePath());
System.out.println(this_dir_2.exists());
}
}
This will work and show you the current path but I don't now why java fails to find current dir in new File(""); besides I am using Java8 compiler...
This works just fine I even tested it new File(new File("").getAbsolutePath());
Now you have current directory in a File object so (Example file object is f then),
f.getAbsolutePath() will give you the path in a String varaible type...
Tested in another directory that is not drive C works fine
My favorite method is to get it from the system environment variables attached to the current running process. In this case, your application is being managed by the JVM.
String currentDir = System.getenv("PWD");
/*
/home/$User/Documents/java
*/
To view other environment variables that you might find useful like, home dir, os version ........
//Home directory
String HomeDir = System.getEnv("HOME");
//Outputs for unix
/home/$USER
//Device user
String user = System.getEnv("USERNAME");
//Outputs for unix
$USER
The beautiful thing with this approach is that all paths will be resolved for all types of OS platform
You might use new File("./"). This way isDirectory() returns true (at least on Windows platform). On the other hand new File("") isDirectory() returns false.
None of the answers posted here worked for me. Here is what did work:
java.nio.file.Paths.get(
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);
Edit: The final version in my code:
URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
myURI = myURL.toURI();
} catch (URISyntaxException e1)
{}
return java.nio.file.Paths.get(myURI).toFile().toString()
System.getProperty("java.class.path")

Creating and Writing Files from Java Runtime

I want to be able to create and write to files from Java. The end goal of this is to be able to write to latex files in conjunction with a math-oriented project, but for now I'm using simple text files as test examples.
I have at least two problems. First, the created test files are being written in my src directory, instead of latexFiles, even after programatically cding into the target directory. Second, I am unable to echo any text into the created text files. Both problems are nonexistent when I simply type the appropriate commands in the terminal myself.
Example Code:
public class LatexManager {
private static void executeCommandAndReadResults(String command) {
Runtime runtime = Runtime.getRuntime();
try {
Process proc = runtime.exec(command);
Scanner scanner = new Scanner(proc.getInputStream());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch(Exception e) {
System.out.printf("Error");
System.out.printf(e.getLocalizedMessage());
}
}
public static void createFile(String fileName) {
LatexManager.executeCommandAndReadResults("touch" + " " + fileName);
}
public static void writeToFile(String content, String fileName) {
LatexManager.executeCommandAndReadResults("echo" + " " + '\'' + content + '\'' + " " + ">" + " " + fileName);
}
public static void moveWorkingDirectory(String to) {
executeCommandAndReadResults("cd" + " " + to);
}
}
in main func:
LatexManager.moveWorkingDirectory("latexFiles");
LatexManager.createFile("hello.txt");
LatexManager.writeToFile("Hello, World!", "hello.txt");
This is because the commands are treated as 3 separate commands. It is as if you open a command window then you execute your command, then you close the window. And you repeat this 2 more times.
And also, you don't specify in which directory your command is executed.
You should use this one instead to specify your running directory:
Runtime.exec(String[] cmdarray, String[] envp, File dir)
Each call to Runtime.exec executes a command in a subshell, that is, a new child process. If you change the directory in that child process, it does not affect the parent process (that is, your Java program).
In fact, there is no way to change the current directory in Java, by design.
You don’t need to change the current directory anyway. And you shouldn’t be trying to write to a project directory, since other people who want to run your compiled program may not have your entire project. A better approach is to create a latexFiles directory in a known location, like the Documents subdirectory of the user’s home directory:
Path latexFilesDir = Path.of(System.getProperty("user.home"),
"Documents", "latexFiles");
Files.createDirectories(latexFilesDir);
You don’t need external commands to write to a file:
Path latexFile = latexFilesDir.resolve(fileName);
Files.write(latexFile, content);
That’s all it takes. For reference, I recommend reading the method summaries in the Files class and the Path class.

java command in cmd how to set default directory

I am running java program from cmd like this java Main. But before that, I have to get to the route directory using cd ..., because my Main class is reding values from property file, which is in root directory. Is there a way or an option of setting the root directory, so then I will no need to get to this directory with cd commands ?
You could pass path to the directory as a parameter and get in from String[] args in main method. You'll pass absolute path to the file and it wouldn't be relevant from which directory you're starting your java process.
Here is the oracle's tutorial showing how you could do that.
Navigating to the directory through command prompt is very easy using a while loop and some simple String processing:
System.out.println("Please navigate to the desired directory then type 'done'...");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
StringBuilder path = new StringBuilder(); //Storage for dir path
path.append(System.getenv("SystemDrive"));
while(scanner.hasNextLine()) {
String command = scanner.nextLine(); //Get input
if(command.equalsIgnoreCase("done")) {
break;
}else if(command.startsWith("cd")){
String arg = command.replaceFirst("cd ", ""); //Get next dir
if(!arg.startsWith(System.getenv("SystemDrive"))) { //Make sure they are not using a direct path
if(!new File(path.toString() + "/" + arg).exists()) { //Make sure the dir exists
arg = arg.equalsIgnoreCase("cd") ? "" : arg;
System.out.println("Directory '" + arg + "' cannot be found in path " + path.toString());
}else {
if(arg.equals("..."))
path = new StringBuilder(path.substring(0, path.lastIndexOf("/"))); //StringBuilder#substring does not alter the actual builder
else
path.append("/" + arg);
System.out.println("\t" + path.toString()); //Add the dir to the path
}
}else { //If they are using a direct path, delete the currently stored path
path = new StringBuilder();
path.append(arg);
System.out.println("\t" + path.toString());
}
}else if(command.equalsIgnoreCase("dir")) {
System.out.println(Arrays.toString(new File(path.toString() + "/").list()));
//List the dirs in the current path
}else {
System.out.println("\t" + command + " is not recognized as an internal command.");
}
}
//Get your file and do whatever
File theFile = new File(path.toString() + "/myFile.properties");
You could use the -cp (classpath) command-line argument of Java.
Then if your directory structure is
<application folder>
|
|--config.props (properties file)
|
\--bin
|
|--Main.class
|
|... other classes
You could just go to the <application folder> and use java -cp bin Main to start the application. And it could refer to config.props as a file in the current folder (because it is in the current folder).
As this is something what you may not want to type all the time, it could be wrapped in a Windows .bat file or *nix .sh script, residing in , next to config.props.

Unable to access/run executable jar placed within the project

I am trying to run an executable jar places in the resources folder of my project. If I place the jar in any directory of my File System and provide the absolute path, it works fine.
Please see the code below:
String jarPath = "C:\\JarFolder\\myJar.jar";
String command = "java -jar";
String space = " ";
String params = "-a abc";
try {
proc = Runtime
.getRuntime()
.exec(command + space + jarPath + space + params);
} catch (IOException e) {
e.printStackTrace();
}
But when I place the jar inside the resources folder, and set the relative jar path as:
String jarPath = "..\\..\\..\\resources\\myJar.jar";
I get an error: Error: Unable to access jarfile ..\\..\\..\\resources\\myJar.jar
I have verified the path, it is valid.
Am I doing something wrong here? Is this the correct way to do this?
Use the ClassLoader to get the path of your resource.
String jarPath = this.getClass().getClassLoader().getResource("myJar.jar").getPath();
String command = "java -jar";
String space = " ";
String params = "-a abc";
try {
proc = Runtime
.getRuntime()
.exec(command + space + jarPath + space + params);
} catch (IOException e) {
e.printStackTrace();
}
If this is being ran from a main static method, then just replace this.getClass() with YourClass.class.
Relative path should work straight forward. Need more details of the error description you see and project folder structure (where the executing jar is placed and where is the import folder placed.)
Other alternate solution is to find the absolute file location of the currently executing jar file. You can fetch it with below code snippet.
MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
Other jar file to be executed must be placed somewhere in the same folder or in some child folders.
Now remove the current jar file name from the absolute path and append the relative path of the other jar file and execute it. It should work.
If you are on window, you can use as follow. I have tested this code and it works.
public class test {
public static void main(String[]args) throws IOException{
String jarPath = test.class.getClass().getResource("/resources/b.jar").getPath();
System.out.println("jarPath "+ jarPath);
//the result path have extra "/" so we have to remove it as follow.
jarPath = jarPath.substring(1);
//and again the result is encoded so we need to decode it back
jarPath = URLDecoder.decode(jarPath);
Runtime
.getRuntime()
.exec("java -jar \""+jarPath+"\"");
}
}
Note: I put my runnable jar in my resources folder with name "b.jar".
And the above codes need some modification to meet your needs.
Good Luck

Location of javaagent jar in bootclasspath

I have a javaagent jar that I put on the bootclasspath using
Boot-Class-Path: myagent.jar
inside the MANIFEST.MF file.
I need to find out the directory on the filesystem in which the jar is located.
However the method described for this here doesnt seem to work for me:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g­etPath());
In this case the ProtectionDomain.getCodeSource() returns null. I guess this is happening because the jar has been put on the boot classpath. Because of this I also cannot do MyClass.getClassLoader() to get the resource location.
I am using Java 6.
Can anyone tell how to get the location of the jar?
You can use the System class loader to find classes on the boot class path. For example, this
System.out.println(
ClassLoader.getSystemClassLoader().getResource("java/lang/String.class")
);
Will print out something like,
jar:file:/C:/Program%20Files/Java/jdk1.6.0_22/jre/lib/rt.jar!/java/lang/String.class
To find the location of MyClass.class on disk, do
String urlString = ClassLoader
.getSystemClassLoader()
.getResource("com/my/package/MyClass.class")
.toString();
urlString = urlString.substring(urlString.indexOf("file:"), urlString.indexOf('!'));
URL url = new URL(urlString);
File file = new File(url.toURI());
System.out.println(file);
System.out.println(file.exists());
Update 2020-06-29 by kriegaex: Rather than writing a new answer to this old question, I want to enhance or update this very good answer, also taking account paths with spaces and Java 9+ modules.
Here is a method returning the class file path as a File instance. If a class file is part of a JAR or Java runtime module (URL starts with protocol jrt:), it just returns the paths to the JAR or to the JMOD file, which is something you might not want, but it is just a showcase you can edit to your heart's content. Of course this is still hacky, e.g. not considering classes loaded from a web URL instead of from file, but you get the idea.
public static File getFileForClass(String className) {
className = className.replace('.', '/') + ".class";
URL classURL = ClassLoader.getSystemClassLoader().getResource(className);
if (classURL == null)
return null;
System.out.println("Class file URL: " + classURL);
// Adapt this if you also have '.war' or other archive types
if (classURL.toString().contains(".jar!")) {
String jarFileName = classURL.getPath().replaceFirst("!.*", "");
System.out.println("Containing JAR file: " + jarFileName);
try {
return new File(new URL(jarFileName).toURI());
}
catch (URISyntaxException | MalformedURLException e) {
throw new RuntimeException(e);
}
}
if (classURL.getProtocol().equals("jrt")) {
String jrtModule = classURL.getFile().replaceFirst("/([^/]+).*", "$1");
System.out.println("Target class is part of Java runtime module " + jrtModule);
String jmodName = System.getProperty("java.home") + "/jmods/" + jrtModule + ".jmod";
System.out.println("Containing Java module file: " + jmodName);
return new File(jmodName);
}
try {
return new File(classURL.toURI());
}
catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
When I call this from one of my IntelliJ IDEA projects with JDK 14 installed under a path containing spaces and deliberately adding a JAR also containing a path with spaces for testing, this code...
public static void main(String[] args) throws IOException {
Instrumentation instrumentation = ByteBuddyAgent.install();
instrumentation.appendToSystemClassLoaderSearch(
new JarFile("C:/Program Files/JetBrains/IntelliJ IDEA 2018.3/lib/idea_rt.jar")
);
Stream
.of(
Weaver.class.getName(),
String.class.getName(),
ByteBuddy.class.getName(),
"com.intellij.execution.TestDiscoveryListener"
)
.forEach(className -> System.out.printf("Found file: %s%n%n", getFileForClass(className)));
}
... yields this console output:
Class file URL: file:/C:/Users/alexa/Documents/java-src/Sarek/sarek-aspect/target/classes/dev/sarek/agent/aspect/Weaver.class
Found file: C:\Users\alexa\Documents\java-src\Sarek\sarek-aspect\target\classes\dev\sarek\agent\aspect\Weaver.class
Class file URL: jrt:/java.base/java/lang/String.class
Target class is part of Java runtime module java.base
Containing Java module file: C:\Program Files\Java\jdk-14.0.1/jmods/java.base.jmod
Found file: C:\Program Files\Java\jdk-14.0.1\jmods\java.base.jmod
Class file URL: jar:file:/C:/Users/alexa/.m2/repository/net/bytebuddy/byte-buddy/1.10.13/byte-buddy-1.10.13.jar!/net/bytebuddy/ByteBuddy.class
Containing JAR file: file:/C:/Users/alexa/.m2/repository/net/bytebuddy/byte-buddy/1.10.13/byte-buddy-1.10.13.jar
Found file: C:\Users\alexa\.m2\repository\net\bytebuddy\byte-buddy\1.10.13\byte-buddy-1.10.13.jar
Class file URL: jar:file:/C:/Program%20Files/JetBrains/IntelliJ%20IDEA%202018.3/lib/idea_rt.jar!/com/intellij/execution/TestDiscoveryListener.class
Containing JAR file: file:/C:/Program%20Files/JetBrains/IntelliJ%20IDEA%202018.3/lib/idea_rt.jar
Found file: C:\Program Files\JetBrains\IntelliJ IDEA 2018.3\lib\idea_rt.jar
You could do something like this:
final String bootClassPath;
final String[] entries;
// different VM may use a different string here...
bootClassPath = System.getProperty("sun.boot.class.path");
entries = bootClassPath.split(File.pathSeparator);
for(final String entry : entries)
{
System.out.println(entry);
}
Which goes through each entry in the boot classpath. For each entry you could then get the JAR file and look at the manifest file and see if it is yours. You could add another entry in the manifest to look for if there isn't already something unique to find.

Categories