In this tutorial, we will explore how to read text files line-by-line in Java using two different approaches: Scanner
and BufferedReader
. Additionally, we’ll discuss sorting an array of integers extracted from the file using insertion sort. By understanding these techniques, you’ll be able to efficiently handle text file processing tasks in your Java applications.
Introduction
Reading data from text files is a common requirement for many Java programs. This tutorial will guide you through two primary methods for reading files: using the Scanner
class and the BufferedReader
class. Both offer unique advantages, so choosing between them depends on specific use cases.
Prerequisites
- Basic understanding of Java programming.
- Familiarity with arrays and sorting algorithms in Java.
Method 1: Using Scanner
The Scanner
class is a simple way to read data from various sources including files, strings, and input streams. It can handle primitive types and strings and provides methods for reading individual tokens or entire lines.
Steps to Read a File with Scanner:
-
Import Required Classes:
import java.io.File; import java.util.Scanner;
-
Open the File:
Ensure that the file path is correct, including its extension.File file = new File("10_Random.txt");
-
Create a Scanner Object:
Use this object to read from the file.try (Scanner sc = new Scanner(file)) { while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); }
-
Read and Store Data:
Convert lines into integers and store them in an array for further processing, such as sorting.
Method 2: Using BufferedReader
BufferedReader
is another approach to read text files line-by-line efficiently. It reads a larger block of characters at once, which can be more efficient than reading one character or token at a time with Scanner
.
Steps to Read a File with BufferedReader:
-
Import Required Classes:
import java.io.BufferedReader; import java.io.FileReader; import java.io.File;
-
Open the File:
File file = new File("10_Random.txt");
-
Create a BufferedReader Object:
try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }
Storing and Sorting Data
Once you have read the data from the file, store it in an array of integers. Use insertion sort to organize this data.
Insertion Sort Algorithm:
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is efficient for small datasets or nearly sorted arrays.
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
Storing Integers in an Array:
While reading numbers from the file, store them into an array.
import java.util.Scanner;
public class FileProcessor {
public static void main(String[] args) {
try (Scanner sc = new Scanner(new File("10_Random.txt"))) {
int[] numbers = new int[sc.nextInt()];
for (int i = 0; i < numbers.length && sc.hasNextInt(); i++) {
numbers[i] = sc.nextInt();
}
insertionSort(numbers);
// Print the sorted array
for (int num : numbers) {
System.out.println(num);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
Conclusion
In this tutorial, you learned how to read a text file line-by-line using both Scanner
and BufferedReader
. We also discussed storing the data in an array of integers and sorting it with insertion sort. Choose between these reading methods based on your specific requirements: use Scanner
for simple token-based operations and BufferedReader
when dealing with large files or requiring efficient read operations.
Tips
- Always ensure the file path is correctly specified, including its extension.
- Use try-with-resources to handle resource management automatically for
Scanner
andBufferedReader
. - When sorting data, consider other algorithms like quicksort or mergesort if working with larger datasets.