How to read / write UTF8 and Non-UTF8 files in Java

In the following java code example, you will learn 4 things about file operations

  1. How to read a regular file, such as plain text from file system, as bytes array
  2. How to write byte array content to the file system
  3. How to read UTF-8 encoded files
  4. How to write file as UTF-8 encoded

package com.icodejava.blog;
/**
 * @author Kushal Paudyal
 * Created on 08/15/2015
 * 
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class FileUtilities {

	private FileUtilities() {

	}

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

		/**
		 * Non UTF8 format file read/write example
		 * Reads content from a file and writes to another file.
		 */
		
		byte[] fileContent = loadFile("/Users/kushal/Desktop/someFile.txt");
		writeFile("/Users/kushal/Desktop/someOutputFile", fileContent);
		
		/**
		 * UTF8 format file read/write example
		 * Reads content from a file and writes to another file.
		 */
		String content = readUTF8File("/Users/paudyak/Desktop/np_name.txt");
		writeUTF8File("/Users/paudyak/Desktop/np_name_out.txt", content);

	}

	/**
	 * This method shows how to read a file as bytes [] 
	 */
	public static byte[] loadFile(String fileName) throws FileNotFoundException, IOException {

		File file = new File(fileName);
		int length = (int) file.length();

		BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
		byte[] bytes = new byte[length];
		reader.read(bytes, 0, length);
		reader.close();

		return bytes;

	}

	/**
	 * This method shows how to write byte [] into a file.
	 */
	public static void writeFile(String fileName, byte[] content) throws IOException {

		File file = new File(fileName);

		BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));

		writer.write(content);

		writer.flush();

		writer.close();

	}

	/**
	 * This method shows how you can read a UTF8 file in Java. 
	 */
	public static String readUTF8File(String fileName) {

		String content = "";

		try {

			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF8"));

			String line;
			while ((line = in.readLine()) != null) {

				System.out.println(line);
				content += line;
				

			}

			in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * This method show how to write UTF8 content to the file system.
	 */
	public static void writeUTF8File(String fileName, String content) {

		try {

			File fileDir = new File(fileName);

			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir),"UTF8"));

			out.append(content);
			out.flush();
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

How To Print A Text File In Java

You will learn the following in this tutorial.

  • – How to read the file content (text) from a file using BufferedReader
  • – How to get a PrinterJob
  • – How to create a PrintBook and append the Printable Page and Page Format to the book
  • – How to show/hide the Print Dialog Box
  • – How to set the text color for printing
  • – How To Implement A Printable Interface that does the real printing.
  • – Some idea about imageable area.
/**
 * @author KushalP
 * www.icodejava.com
 * Last Modified On 2009-05-19
 */
package com.kushal.utils;

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.*;

/**
 * Using JAVA to print simple text file to a printer
 */

public class PrintFileToPrinter implements Printable {

	static AttributedString myStyledText = null;

	public static void main(String args[]) {
		/**Location of a file to print**/
		String fileName = "C:/Temp/abc.txt";

		/**Read the text content from this location **/
		String mText = readContentFromFileToPrint(fileName);

		/**Create an AttributedString object from the text read*/
		myStyledText = new AttributedString(mText);

		printToPrinter();

	}

	/**
	 * This method reads the content of a text file.
	 * The location of the file is provided in the parameter
	 */
	private static String readContentFromFileToPrint(String fileName) {
		String dataToPrint = "";

		try {
			BufferedReader input = new BufferedReader(new FileReader(fileName));
			String line = "";
			/**Read the file and populate the data**/
			while ((line = input.readLine()) != null) {
				dataToPrint += line + "n";
			}
		} catch (Exception e) {
			return dataToPrint;
		}
		return dataToPrint;
	}

	/**
	 * Printing the data to a printer.
	 * Initialization done in this method.
	 */
	public static void printToPrinter() {
		/**
		 * Get a Printer Job
		 */
		PrinterJob printerJob = PrinterJob.getPrinterJob();

		/**
		 * Create a book. A book contains a pair of page painters
		 * called printables. Also you have different pageformats.
		 */
		Book book = new Book();
		/**
		 * Append the Printable Object (this one itself, as it
		 * implements a printable interface) and the page format.
		 */
		book.append(new PrintFileToPrinter(), new PageFormat());
		/**
		 * Set the object to be printed (the Book) into the PrinterJob. Doing this
		 * before bringing up the print dialog allows the print dialog to correctly
		 * display the page range to be printed and to dissallow any print settings not
		 * appropriate for the pages to be printed.
		 */
		printerJob.setPageable(book);

		/**
		 * Calling the printDialog will pop up the Printing Dialog.
		 * If you want to print without user confirmation, you can directly call printerJob.print()
		 *
		 * doPrint will be false, if the user cancels the print operation.
		 */
		boolean doPrint = printerJob.printDialog();

		if (doPrint) {
			try {
				printerJob.print();
			} catch (PrinterException ex) {
				System.err.println("Error occurred while trying to Print: "
						+ ex);
			}
		}
	}

	/**
	 * This method comes from the Printable interface.
	 * The method implementation in this class
	 * prints a page of text.
	 */
	public int print(Graphics g, PageFormat format, int pageIndex) {

		Graphics2D graphics2d = (Graphics2D) g;
		/**
		 * Move the origin from the corner of the Paper to the corner of the imageable
		 * area.
		 */
		graphics2d.translate(format.getImageableX(), format.getImageableY());

		/** Setting the text color**/
		graphics2d.setPaint(Color.black);
		/**
		 * Use a LineBreakMeasurer instance to break our text into lines that fit the
		 * imageable area of the page.
		 */
		Point2D.Float pen = new Point2D.Float();
		AttributedCharacterIterator charIterator = myStyledText.getIterator();
		LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
				graphics2d.getFontRenderContext());
		float wrappingWidth = (float) format.getImageableWidth();
		while (measurer.getPosition() < charIterator.getEndIndex()) {
			TextLayout layout = measurer.nextLayout(wrappingWidth);
			pen.y += layout.getAscent();
			float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout
					.getAdvance());
			layout.draw(graphics2d, pen.x + dx, pen.y);
			pen.y += layout.getDescent() + layout.getLeading();
		}
		return Printable.PAGE_EXISTS;
	}

}

Here is the printer dialog box that popped up on my screen when I tried to run this program. And of course, it did print the file that I specified.

P.S. This article was previously published in my another blog at Sanjaal.com

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 = &quot;C:/temp/myTabSeparatedFile.txt&quot;;

		/**
		 * 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(&quot;t&quot;);
			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 + &quot;t&quot; + value2 + &quot;t&quot; + value3 + &quot;t&quot;
					+ 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 (&quot;HIGH RISK ACTIVITIES&quot;). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */

}