Java: read a text file line by line
January 29, 2010 21:08:43
This class reads a text file line by line and echos the contents to standard out.
import java.io.*; public class ReadTextFile { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: java " + ReadTextFile.class.getName() + " <input file>"); System.exit(1); } String fileName = args[0]; // nested initialization, // or in design pattern jargon, decorate FileInputStream with // BufferedInputStream. BufferedReader in = new BufferedReader(new FileReader(fileName)); try { // read file line by line String line = in.readLine(); while (line != null) { processLine(line); line = in.readLine(); } } finally { // always close input stream in.close(); } } private static void processLine(String line) { System.out.println(line); } }
Easy email testing with http://www.ximailstop.com