Tuesday 7 June 2022

How to read the file content using an iterator in Java?

What is iterator?

Iterator is used to traverse the collection of elements. There is also a legacy class called Enumeration, it is also used to traverse collection of elements. Only difference is by using iterator you can remove an element while traversing, by using enumerator you can’t.

 

Let me brief the methods in iterator interface.

Method

Description

boolean hasNext()

Returns true if the iteration has more elements.

E next()

Returns the next element in the iteration.

default void remove()

Removes from the underlying collection the last element returned by this iterator. Java provides default implementation for this method. The default implementation throws an instance of UnsupportedOperationException and performs no other action.

 

Iterable interface

All the Java collections implementing Iterable interface, to return an iterator. Implementing this interface allows an object to be the target of the "foreach" statement. Following table summarizes the methods in Iterable interface.

 

Method

Description

Iterator<T> iterator()

Returns an iterator over a set of elements of type T.

 

Now let’s come to the problem, I want to implement my own iterator to read the file in iterator fashion.

 

Find the below working application.

 

demo.txt

line1
line2
line3

 

FileReadIterable.java

package com.sample.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;

/**
 * FileReadIterable class is used to read the file using an iterator.
 */
public class FileReadIterable implements Iterable<String> {

	private BufferedReader bufferedReader;

	public FileReadIterable(BufferedReader bufferedReader) {
		this.bufferedReader = bufferedReader;
	}

	@Override
	public Iterator<String> iterator() {
		return new FileReadIterator(bufferedReader);
	}

	private static class FileReadIterator implements Iterator<String> {

		private BufferedReader bufferedReader;
		private String line;

		public FileReadIterator(BufferedReader bufferedReader) {
			this.bufferedReader = bufferedReader;
		}

		@Override
		public boolean hasNext() {
			try {
				line = bufferedReader.readLine();
			} catch (IOException e) {
				return false;
			}
			return line != null;
		}

		@Override
		public String next() {
			return line;
		}

	}

}

 

FileIteratorDemo.java

package com.sample.app;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;

public class FileIteratorDemo {

	public static String resourceFilePath(String resourceFile) {
		ClassLoader classLoader = FileIteratorDemo.class.getClassLoader();
		URL url = classLoader.getResource(resourceFile);
		return url.getPath();
	}

	public static void main(String[] args) throws IOException {

		String filePath = resourceFilePath("demo.txt");

		try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
			FileReadIterable fileReadIterable = new FileReadIterable(bufferedReader);

			Iterator<String> fileIterator = fileReadIterable.iterator();

			while (fileIterator.hasNext()) {
				System.out.println(fileIterator.next());
			}

		}

	}

}

Output

line1
line2
line3


You may like

Interview Questions

How to find the Java major and minor versions from a .class file

Can I run a class file that is compiled in lower environment?

How to solve the Error: Could not find or load main?

float vs double in Java

Quick guide to race condition in Java with examples

No comments:

Post a Comment