在Java中如何使用Scanner读取文件

逐行读取

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();
      }
   }
}
日期:2020-06-02 22:15:22 来源:oir作者:oir