In Java I can use the following code:
public class Ex {
public static void main(String [ ] args) {
String path = Ex.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
}
}
but in Kotlin, the main function is defined outside out of a class. How can I get it's current file name?
Since Kotlin 1.1, you can use the ::class syntax to get the KClass . There are several different implementations to get the class name as per your requirements. Additionally, you can use KClass. js to access the JsClass instance corresponding to the class.
In the above program, we used Path 's get() method to get the current path of our program. This returns a relative path to the working directory. We then change the relative path to absolute path using toAbsolutePath() . Since, it returns a Path object, we need to change it to a string using toString() method.
To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);
As a workaround, put main
method into companion object.
This code will show a same path as your Java code:
class ExKt {
companion object {
@JvmStatic fun main(args: Array<String>) {
val path = ExKt::class.java.protectionDomain.codeSource.location.path
println("Kotlin: " + path)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With