在Java中,可以使用java.io.File
类或者java.nio.file.Paths
类来获取当前程序(即运行Java应用的JVM)所在的路径。以下是两种方法:
- 使用
java.io.File
类:
import java.io.File;
public class Main {
public static void main(String[] args) {
// 获取当前类的class文件所在目录
File currentDir = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String path = currentDir.getAbsolutePath();
System.out.println("当前路径: " + path);
}
}
- 使用
java.nio.file.Paths
类:
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
// 获取当前工作目录(可能与.class文件所在目录不同,通常是指运行Java命令时所在的目录)
String currentPath = Paths.get(".").toAbsolutePath().normalize().toString();
System.out.println("当前路径: " + currentPath);
}
}
如果想要获取的是Java应用程序启动时的当前工作目录,那么第二种方法更为直接。
但如果希望得到的是包含.class
文件的jar包或目录的实际路径,第一种方法更为合适。注意在处理路径时,可能需要对路径字符串进行适当的处理以适应不同的操作系统。
欢迎关注公-众-号【TaonyDaily】、留言、评论,一起学习。
Don’t reinvent the wheel, library code is there to help.
文章来源:刘俊涛的博客
若有帮助到您,欢迎点赞、转发、支持,您的支持是对我坚持最好的肯定(^_^)