Java开发
Java获取路径的6种方式
2025-01-30 26 0
简介 Java获取路径的6种方式
public class Demo1 {
public static void main(String[] args) {
/*
1.使用 System 属性
*/
// 获取用户的主目录
String userHome = System.getProperty("user.home");
System.out.println("User Home: " + userHome);
// 获取Java的安装目录
String javaHome = System.getProperty("java.home");
System.out.println("Java Home: " + javaHome);
/*
* 2.使用 ClassLoader 获取资源路径
*/
// 获取类路径下的资源文件路径
ClassLoader classLoader = Demo1.class.getClassLoader();
URL resourceUrl = classLoader.getResource("config.properties");
String resourcePath = resourceUrl != null ? resourceUrl.getPath() : null;
System.out.println("Resource Path: " + resourcePath);
/*
3.使用 File 类
*/
// 创建一个File对象
File file = new File("example.txt");
// 获取绝对路径
String absolutePath = file.getAbsolutePath();
System.out.println("Absolute Path: " + absolutePath);
// 获取相对路径(相对于当前工作目录)
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
System.out.println("Canonical Path: " + canonicalPath);
} catch (IOException e) {
e.printStackTrace();
}
// 获取父目录路径
String parentPath = file.getParent();
System.out.println("Parent Path: " + parentPath);
/*
4.使用 Paths 类(Java 7及以上)
*/
// 获取当前工作目录
Path currentDir = Paths.get(".").toAbsolutePath();
System.out.println("Current Directory: " + currentDir);
// 拼接路径
Path filePath = Paths.get(currentDir.toString(), "example.txt");
System.out.println("File Path: " + filePath);
/*
5.使用 URI
*/
File file2 = new File("example.txt");
URI uri = file2.toURI();
String uriPath = uri.getPath();
System.out.println("URI Path: " + uriPath);
/*
6. 获取当前执行文件的路径(Java应用)
*/
String path = Demo1.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("Executable Path: " + path);
}
}