Reading files made easy in Java

Courtesy : http://code.hammerpig.com/how-to-read-really-large-files-in-java.html

import java.util.*;
import java.io.*;

public class BigFile implements Iterable
{
private BufferedReader _reader;

public BigFile(String filePath) throws Exception
{
_reader = new BufferedReader(new FileReader(filePath));
}

public void Close()
{
try
{
_reader.close();
}
catch (Exception ex) {}
}

public Iterator iterator()
{
return new FileIterator();
}

private class FileIterator implements Iterator
{
private String _currentLine;

public boolean hasNext()
{
try
{
_currentLine = _reader.readLine();
}
catch (Exception ex)
{
_currentLine = null;
ex.printStackTrace();
}

return _currentLine != null;
}

public String next()
{
return _currentLine;
}

public void remove()
{
}
}
}

Here is how you might use it:

BigFile file = new BigFile("C:\Temp\BigFile.txt");

for (String line : file)
System.out.println(line);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.