Breaking News
Home / Java / Java Snippets / Simple File Writer

Simple File Writer

Java File WriterThis snippet show how to write Strings to a file. It writes the String text as new line using the n character. This class can be used to build Logger or write data into the file for storage.

package com.livrona.snippets.io;

import java.io.FileOutputStream;

/**
 * This snippet show how to write String to a file
 * 
 * @author java4learners
 */
public class SimpleFileWriter {

	private FileOutputStream fos;
	private String fileName;

	/**
	 * Store the filename
	 * 
	 * @param fileName
	 */
	public SimpleFileWriter(String fileName) {
		this.fileName = fileName;

	}

	/**
	 * Open the File Stream
	 * 
	 * @throws Exception
	 */
	public void open() throws Exception {
		fos = new FileOutputStream(fileName);
	}

	/**
	 * Write a given text o the file
	 * 
	 * @param text
	 * @throws Exception
	 */
	public void writeLine(String text) throws Exception {

		// write the text
		fos.write(text.getBytes());

		// write the new line
		fos.write("n".getBytes());
	}

	/**
	 * Flush and close the stream
	 * 
	 * @throws Exception
	 */
	public void close() throws Exception {

		fos.flush();
		fos.close();
	}

	public static void main(String[] args) {

		if (args.length != 1) {
			System.out
					.println("Usage: java com.livrona.snippets.io.FileWriter ");
			System.exit(0);
		}

		String dataFile = args[0];
		System.out.println("File : " + dataFile);

		// write 3 lines to file
		try {
			SimpleFileWriter writer = new SimpleFileWriter(dataFile);
			writer.writeLine("Hello");
			writer.writeLine("This is in new line");
			writer.writeLine("bye");
			writer.close();
		} catch (Exception e) {
			System.out.println("Failed to write : " + e.getMessage());
			e.printStackTrace();
		}

	}
}

 [pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Leave a Reply