0

so I have a java project, and I'm currently able to get the path to the file by using

String pathname = test.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 

This is returning /home/mrpickles/Desktop/HANSTUFF/securesdk/src, which is the path TO my file, which is called "JavaWrapper.java" with the class "JavaTest". What I would like it to return is "/home/mrpickles/Desktop/HANSTUFF/securesdk/src/JavaWrapper.java so that the path INCLUDES the file name. How do I do this?

1

1 Answer 1

1

You can't, actually.

You do know that .java files are converted to .class files after compilation, right?

The only thing you can preserve is package structure. and also a single .java file can contain only one public class that matches the .java file name, but it could contain multiple classes with different names.

Once your .java files are compiled into .class files, you can move them around different locations by keeping them in same package structure. So your source .java location could be different from .class file location.

Update:

You can print basic full class name and the location from where the class file is loaded with:

public class Test { public static void main(String[] args) { Test test =new Test(); System.out.println("Class Name: "+test.getClass().getSimpleName()); System.out.println("With Package Name: "+test.getClass().getName()); System.out.println("Location: "+ClassLoader.getSystemResource("Test.class")); } } 

Output:

Class Name: Test With Package Name: com.test.Test Location: file:/C:/workspace/Test-Project/build/classes/Test.class 
Sign up to request clarification or add additional context in comments.

2 Comments

i know. I think what I meant to say is how can I get the path to have the name of the class. For example my class within JavaWrapper.java is called JavaTest.class. Is there any way for me to get the path including that? Thanks.
@Mr.Pickles Updated the answer.