java获取当前文件路径
问题描述:java获取当前文件路径
推荐答案 本回答由问问达人推荐
在Java中,可以使用`java.nio.file.Paths`类和`java.io.File`类等来获取当前文件路径。以下是三种不同的方法:
1. 使用`Paths.get("").toAbsolutePath()`方法:这是一种简单的方法,可以获取当前工作目录的绝对路径。
import java.nio.file.Path;
import java.nio.file.Paths;
public class CurrentFilePathExample {
public static void main(String[] args) {
Path currentPath = Paths.get("").toAbsolutePath();
System.out.println("当前文件路径:" + currentPath);
}
}
2. 使用`System.getProperty("user.dir")`方法:这是另一种获取当前工作目录的方法,与第一种方法类似。
public class CurrentFilePathExample {
public static void main(String[] args) {
String currentPath = System.getProperty("user.dir");
System.out.println("当前文件路径:" + currentPath);
}
}
3. 使用`File`类获取当前文件路径:可以创建一个临时文件,然后使用`File`类的`getAbsolutePath()`方法获取其绝对路径,再从路径中截取出当前文件路径。
import java.io.File;
import java.io.IOException;
public class CurrentFilePathExample {
public static void main(String[] args) {
try {
File tempFile = File.createTempFile("temp", ".txt");
String tempPath = tempFile.getAbsolutePath();
String currentPath = tempPath.substring(0, tempPath.lastIndexOf(File.separator));
tempFile.deleteOnExit(); // 删除临时文件
System.out.println("当前文件路径:" + currentPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上三种方法都可以获取当前文件路径,根据实际需求选择合适的方法来使用。