BibleGateway.com Verse Of The Day

Wednesday, February 14, 2007

Reading a Text File Line By Line

Sometimes I need to read a text file line by line from Java code. Whether it's reading transactions to blast onto an MQ queue, or parsing out CSV files, the actual reading of the file remains the same. But it's something that I always have to look up an example for, because I don't work with all the streams, readers, and writers classes often enough to memorize.

Here's the simplest running example, basically a crappy implementation of the the Unix "cat" command (read a file and spit it out to the console, line by line). To get it to do something useful, replace the System.out.println with something more useful, like putting to a queue, or running the line through a CSV parser, or running a SQL query, etc.



import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class UnixCat
{
public void cat(String filename) throws IOException
{
BufferedReader is = new BufferedReader(new FileReader(filename));

String line = "";
while (line != null)
{
line = is.readLine();
System.out.println(line);
}
is.close();
}

public static void main(String[] args)
{
UnixCat uc = new UnixCat();

// Assume args is a list of filenames
for (int ii = 0; ii < args.length; ii++)
{
try
{
uc.cat(args[ii]);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
}


No comments: