View RSS Feed

My Java Tips

Data Streams

Rate this Entry
by , 11-11-2011 at 05:35 PM (879 Views)
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface.


If you need to work with data that is not represented as bytes or characters then you can use Data Streams. These streams filter an existing byte stream so that each primitive data types can be read from or written to the stream directly.

These Data Streams are as follows:

1. DataInputStream

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

DataInputStream class constructor.

DataInputStream(InputStream in)
Creates a DataInputStream that uses the specified underlying InputStream.

Below is the list of methods of the DataInputStream class.

int read(byte[] b)
Reads some number of bytes from the contained input stream and stores them into the buffer array b.

int read(byte[] b, int off, int len)
Reads up to len bytes of data from the contained input stream into an array of bytes.

boolean readBoolean()
See the general contract of the readBoolean method of DataInput.

byte readByte()
See the general contract of the readByte method of DataInput.

char readChar()
See the general contract of the readChar method of DataInput.

double readDouble()
See the general contract of the readDouble method of DataInput.

float readFloat()
See the general contract of the readFloat method of DataInput.

void readFully(byte[] b)
See the general contract of the readFully method of DataInput.

void readFully(byte[] b, int off, int len)
See the general contract of the readFully method of DataInput.

int readInt()
See the general contract of the readInt method of DataInput.

long readLong()
See the general contract of the readLong method of DataInput.

short readShort()
See the general contract of the readShort method of DataInput.

int readUnsignedByte()
See the general contract of the readUnsignedByte method of DataInput.

int readUnsignedShort()
See the general contract of the readUnsignedShort method of DataInput.

String readUTF()
See the general contract of the readUTF method of DataInput.

static String readUTF(DataInput in)
Reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String.

int skipBytes(int n)
See the general contract of the skipBytes method of DataInput.

2. DataOutputStream

A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

Below is DataOutputStream class constructor.

DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying output stream.

Below is the list of methods of the DataOutputStream class.

void flush()
Flushes this data output stream.

int size()
Returns the current value of the counter written, the number of bytes written to this data output stream so far.

void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to the underlying output stream.

void write(int b)
Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

void writeBoolean(boolean v)
Writes a boolean to the underlying output stream as a 1-byte value.

void writeByte(int v)
Writes out a byte to the underlying output stream as a 1-byte value.

void writeBytes(String s)
Writes out the string to the underlying output stream as a sequence of bytes.

void writeChar(int v)
Writes a char to the underlying output stream as a 2-byte value, high byte first.

void writeChars(String s)
Writes a string to the underlying output stream as a sequence of characters.

void writeDouble(double v)
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.

void writeFloat(float v)
Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.

void writeInt(int v)
Writes an int to the underlying output stream as four bytes, high byte first.

void writeLong(long v)
Writes a long to the underlying output stream as eight bytes, high byte first.

void writeShort(int v)
Writes a short to the underlying output stream as two bytes, high byte first.

void writeUTF(String str)
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

Example

The following DataStreams example demonstrates data streams by writing out a set of data records, and then reading them in again.

Java Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.PrintStream;

public class DataStreamsDemo {
	static final String dataFile = "invoicedata";

	static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };

	static final int[] units = { 12, 8, 13, 29, 50 };

	static final String[] descs = { "Java T-shirt", "Java Mug",
			"Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

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

		DataOutputStream out = null;

		try {
			out = new DataOutputStream(new BufferedOutputStream(
					new FileOutputStream(dataFile)));

			for (int i = 0; i < prices.length; i++) {
				out.writeDouble(prices[i]);
				out.writeInt(units[i]);
				out.writeUTF(descs[i]);
			}
		} finally {
			out.close();
		}

		DataInputStream in = null;
		double total = 0.0;
		try {
			in = new DataInputStream(new BufferedInputStream(
					new FileInputStream(dataFile)));

			double price;
			int unit;
			String desc;

			try {
				while (true) {
					price = in.readDouble();
					unit = in.readInt();
					desc = in.readUTF();
					System.out.format("You ordered %d units
                                         of %s at $%.2f%n",unit, desc, price);
					total += unit * price;
				}
			} catch (EOFException e) {
			}
			System.out.format("For a TOTAL of: $%.2f%n", total);
		} finally {
			in.close();
		}
	}
}
Output:


You ordered 12 units of Java T-shirt at $19.99
You ordered 8 units of Java Mug at $9.99
You ordered 13 units of Duke Juggling Dolls at $15.99
You ordered 29 units of Java Pin at $3.99
You ordered 50 units of Java Key Chain at $4.99
For a TOTAL of: $892.88

Submit "Data Streams" to Facebook Submit "Data Streams" to Digg Submit "Data Streams" to del.icio.us Submit "Data Streams" to StumbleUpon Submit "Data Streams" to Google

Comments