使用扫描仪读取文件
逐行读取文件
public class Main {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("example.txt"));
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
//do stuff
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
逐词地
public class Main {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("example.txt"));
while(scanner.hasNext())
{
String line = scanner.next();
//do stuff
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
你还可以使用 scanner.useDelimeter()
方法更改分隔符