How to read a tab separated or tab delimited file in Java program and print the content to console

In a tab delimited file every line or record has the same number of fields that are separated by the tab character.

  • In the following java program,
  • We read the records or lines in a loop
  • For each record, we split the line on the tab character forming an array.
  • Then we format the fields according to the data type (e..g String, int, double etc)
  • Finally we print the data thus read from file to console.

Here is how the program looks like:

package com.icodejava.io;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * www.icodejava.com
 * Last Modfied On: 2010-07-30
 * 
 * TabSeparatedFileReader.java
 * This class reads tab separated values (4 columns) from a file
 * and prints the values to the console.
 */
import java.io.BufferedReader;
import java.io.FileReader;

public class TabSeparatedFileReader {

	public static void main(String args[]) throws Exception {
		/**
		 * Source file to read data from.
		 */
		String dataFileName = "C:/temp/myTabSeparatedFile.txt";

		/**
		 * Creating a buffered reader to read the file
		 */
		BufferedReader bReader = new BufferedReader(
				new FileReader(dataFileName));

		String line;

		/**
		 * Looping the read block until all lines in the file are read.
		 */
		while ((line = bReader.readLine()) != null) {

			/**
			 * Splitting the content of tabbed separated line
			 */
			String datavalue[] = line.split("t");
			String value1 = datavalue[0];
			String value2 = datavalue[1];
			int value3 = Integer.parseInt(datavalue[2]);
			double value4 = Double.parseDouble(datavalue[3]);

			/**
			 * Printing the value read from file to the console
			 */
			System.out.println(value1 + "t" + value2 + "t" + value3 + "t"
					+ value4);
		}
		bReader.close();
	}

	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
	 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
	 * LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
	 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
	 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 * 
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */

}