共计 751 个字符,预计需要花费 2 分钟才能阅读完成。
Java 中可以使用以下方法来获取当前程序的路径:
1. 使用 System.getProperty("user.dir") 方法,它会返回当前程序的工作目录路径。
2. 使用 File 类的 getAbsolutePath() 方法,可以通过创建一个 File 对象来获取当前程序的绝对路径。
3. 使用 ClassLoader 类的 getResource() 方法,可以获取当前程序所在的类路径(classpath)的 URL,进而通过 URL 对象的 getPath() 方法获取路径字符串。
下面是示例代码:java
// 方法 1
String currentDir = System.getProperty("user.dir");
System.out.println(" 当前程序路径:" + currentDir);
// 方法 2
File currentFile = new File("");
String currentPath = currentFile.getAbsolutePath();
System.out.println(" 当前程序路径:" + currentPath);
// 方法 3
ClassLoader classLoader = MyClass.class.getClassLoader(); // 这里的 MyClass 替换为当前类的名称
URL url = classLoader.getResource("");
String currentPath = url.getPath();
System.out.println(" 当前程序路径:" + currentPath);
请注意,以上代码中的路径是当前程序的路径,而不是某个特定类的路径。如果需要获取某个类的路径,可以使用 MyClass.class.getResource("") 来替换方法 3 中的代码。
丸趣 TV 网 – 提供最优质的资源集合!