从 java 核心技术了解到
Scanner 类可用于读取文件
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
try {
// 此处表明该文件在项目根目录下
File file = new File("text.txt");
// Scanner in = new Scanner(Paths.get("niyflle.txt"), "UTF-8");
// System.out.println(System.getProperty("user.dir")); //获取当前项目的相对位置
// System.out.println(file.getAbsolutePath()); // 获取当前file对象指向的的相对位置
Scanner sc = new Scanner(file,"utf-8");
while (sc.hasNext()) {
String temp = sc.nextLine();
System.out.println(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
但需注意不可直接在Scanner中传入路径参数 “Scanner(“text.txt”)” ,里面的 “text.txt” 会被当成字符串