Use the following methods in Java to read text data: Scanner class: Create a Scanner object, use the nextLine() method to read data line by line, and close the Scanner. BufferedReader class: Create a BufferedReader object, use the readLine() method to read data line by line, and close the BufferedReader.
How to read text data using Java
Introduction
In Java Reading in text data is a basic task used in processing various text files. This article will introduce the common methods of reading text data in Java using the following methods:
Method 1: Using the Scanner class
The Scanner class is a method used to read in text data from various Utility classes for reading data (including text files) from input sources. The following are the steps to use Scanner to read text data:
new Scanner(File file)
to create a Scanner object, wherefile
is the text file to be read. nextLine()
method to read data line by line until the end of the file is reached. close()
method to close the Scanner. Example
<code class="java">import java.io.File; import java.util.Scanner; public class ReadTextFile { public static void main(String[] args) { try { // 创建 Scanner 对象 Scanner scanner = new Scanner(new File("text.txt")); // 按行读取数据 while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } // 关闭 Scanner scanner.close(); } catch (Exception e) { e.printStackTrace(); } } }</code>
Method 2: Using the BufferedReader class
The BufferedReader class provides an efficient method to read text data line by line. The following are the steps to use BufferedReader to read text data:
new BufferedReader(FileReader reader)
to create a BufferedReader object, wherereader
is a FileReader object pointing to a text file. readLine()
method to read data line by line until the end of the file is reached. close()
method to close the BufferedReader. Example
<code class="java">import java.io.BufferedReader; import java.io.FileReader; public class ReadTextFile { public static void main(String[] args) { try { // 创建 BufferedReader 对象 BufferedReader reader = new BufferedReader(new FileReader("text.txt")); // 按行读取数据 String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 关闭 BufferedReader reader.close(); } catch (Exception e) { e.printStackTrace(); } } }</code>
The above is the detailed content of How to read text data in java. For more information, please follow other related articles on the PHP Chinese website!