java基础学习: Java 中获取文件路径的几种方式
warning:
这篇文章距离上次修改已过452天,其中的内容可能已经有所变动。
在Java中,获取文件路径的方式主要有以下几种:
- 使用
java.io.File类的getAbsolutePath()方法:
File file = new File("relative/path/to/file");
String path = file.getAbsolutePath();
System.out.println(path);- 使用
java.nio.file.Paths类的get()方法:
Path path = Paths.get("relative/path/to/file").toAbsolutePath();
System.out.println(path.toString());- 使用
java.io.File类的getCanonicalPath()方法:
File file = new File("relative/path/to/file");
String path = file.getCanonicalPath();
System.out.println(path);- 使用系统属性
user.dir获取当前工作目录:
String path = System.getProperty("user.dir");
System.out.println(path);- 使用
java.net.URL类获取资源路径:
URL resource = getClass().getResource("/relative/path/to/resource");
String path = resource.getPath();
System.out.println(path);- 使用
java.nio.file.Path类的toString()方法:
Path path = Paths.get("relative/path/to/file");
System.out.println(path.toString());这些方法可以获取相对路径或绝对路径,具体使用取决于需要。
评论已关闭