This article describes the usage of Scanner in Java programming to read data into text files. Share it for your reference, as follows:
Use Scanner class to read files
We use Scanner class to read data from the keyboard, or we can use the Scanner class to read data from a text file. Let's first look at an instance code
package com.li;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.util.*;public class Main { public static void main(String[] args) { // TODO automatic generated method stub Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream("stuff.txt")); }catch(FileNotFoundException e) { System.out.println("File stuff.txt")); }catch(FileNotFoundException e) { System.out.println("File stuff.txt was no found"); System.exit(0); } String line = inputStream.nextLine(); System.out.println(line); inputStream.close(); }} A stuff.txt file here can be a file created by another Java program or a file written by itself in a text compiler. Here, the nextLine() method is used, which is similar to reading data from the keyboard. This means that a line of data is read from the text file, and the read data will be printed on the screen.
At this time, it is important to note that after reading the file, we must also close the file. At the same time, don't forget to handle exceptions, we cannot ensure that there will be no errors during the opening of the file.
For more information about Java algorithms, readers who are interested in this site can view the topics: "Summary of Java Files and Directory Operation Skills", "Tutorial on Java Data Structures and Algorithms", "Summary of Java Operation DOM Node Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.