Java OutputStream

Java uses streams as the foundation for communication and IO. Two very important abstract classes are InputStream and OutputStream. These two classes  provide a foundation of methods that are called to read and write byte sized data or byte arrays.

A subclass of OutputStream must at least override the write() method to write at least one byte. A commonly used subclass of OutputStream is the FileOutputStream class which provides a platform independent way to write data to a file.

The following code demonstrates a character generator that writes data to a FileOutputStream object.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CharGenerator {
	private File file = null;
	private FileOutputStream fos = null;

	public CharGenerator() {

	}

	public static void main(String[] args) {
		CharGenerator charGenerator = new CharGenerator();
		if (args.length <= 0) {
			charGenerator.openFile(null); // using default file
		} else {
			charGenerator.openFile(args[0]); // providing filename
		}

		// write to file
		try {
			charGenerator.writeAscii();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			charGenerator.closeFile();
		}

	}

	private void closeFile() {
		if(fos != null){
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// open file
	public void openFile(String filename) {
		try {
			if ((filename == null) || filename.trim().equals("")) {
				file = new File("output.txt");
				System.out.println("Writing to default file:"
						+ file.getAbsolutePath());
			} else {
				file = new File(filename);
				System.out
						.println("Writing to file: " + file.getAbsolutePath());
			}
			fos = new FileOutputStream(file, false);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void writeAscii() throws IOException {
		char character = 0x21;
		int charBase = 0x21;
		for (int i = 1; i = 72 && charBase <= 54) {
				System.out.println();
				fos.write((char) '\r'); // carriage return, ms-dos
				fos.write((char) '\n');
				++charBase;
				i = 0;
				character = (char) charBase;
			}
		}
	}
}

[/sourcecode]

Comments Trackbacks / Pingbacks (4)