有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将URL对象转换为字符串

我想将URL转换为字符串。我在网上搜索过,没有找到任何有用的东西。显然有一个toString(URL)方法,但我无法让它工作

public String getLocationJar(){
    URL fileLocation = getClass().getProtectionDomain().getCodeSource().getLocation();

    return toString(fileLocation);
} 

共 (1) 个答案

  1. # 1 楼答案

    如果我没听错,你只需要打电话给fileLocation.toString()或者fileLocation.getPath()。以下代码:

    URL fileLocation = Test.class.getProtectionDomain().getCodeSource().getLocation();
    
    System.out.println(fileLocation.toString());
    System.out.println(fileLocation.getPath());
    

    输出所需路径:

    file:/C:/Users/xxx/Dev/Workspace/proj/target/classes/
    /C:/Users/xxx/Dev/Workspace/proj/target/classes/
    

    所以,只需将代码更改为return fileLocation.toString()