Java中Path.of方法的使用报错处理
Java 中 Path.of 方法的使用
起因
学习 Java 核心技术这本书的 3.7.3 章节时,对于书中代码的实现出现了一些问题,书中所呈现的是这样的语句:点击查看代码
Scanner in = new Scanner(Path.of("myfile"),StandardCharsets.UTF_8)
The method of is undefined for the type Path 显示 Path 类中并没有 of 这种方法, 去查了下官方文档,发现在 Java18 的文档中可以找到这个函数。
尝试解决的方案
下面我们通过代码来验证这种方法:
点击查看代码
import javax.lang.model.element.VariableElement;
import static java.lang.Math.*;
import java.io.;
import java.nio.;
import java.util.*;
public class JavaDump {
public static void main(String args[]) throws IOException {
String dir = System.getProperty("user.dir");
Scanner in = new Scanner(Paths.get(dir, "myfile.txt"), "UTF-8");
System.out.println(in.nextLine());
System.out.println(in.nextLine());
System.out.println(in.nextLine());
System.out.println(in.nextLine());
System.out.println(in.nextLine());
in.close();
}
}
结果如下图:
结论
在我们使用各种方法的时候,要注意不同 JDK 版本间的差别,遇到问题需要多查 JDK 文档,选择自己的 JDK 版本号,避免遇到同样的问题。