go to previous page   go to home page   go to next page        

Will the following statement work?

DataOutputStream dataOut = new DataOutputStream( "myFile.dat" );


No. You need a FileOutputStream to connect to a disk file, then connect a DataOutputStream to the FileOutputStream.


A DataOutputStream is used to write bytes representing primitive data types. It writes to another output stream (such as a BufferedOutputStream or FileOutputStream). A DataOutputStream ensures portability because it uses the same data format on all computer platforms. For example writeInt() writes the four bytes of an int in the same order (high byte to low byte) on all computers.


public DataOutputStream(OutputStream out)
    Construct a data output stream.


public void flush() throws IOException
    Flushes the stream.

public final int size()
    Return the number of bytes written so far.

public void write(int b) throws IOException
    Writes the low eight bits of the argument.

public final void writeBoolean(boolean b) throws IOException
    Writes a boolean as a 1-byte value. 
    True is written as 00000001, false is written as 00000000.

public final void writeByte(int b) throws IOException

public void writeBytes(String s) throws IOException
    Writes the low eight bits of each character in the string.

public final void writeChar(int c) throws IOException

public void writeDouble(double v) throws IOException

public void writeFloat(float f) throws IOException

public void writeInt(int i) throws IOException

public void writeLong(long l) throws IOException

public final void writeShort(int s) throws IOException

Bug Alert: The argument to writeByte() is an int. The low eight bits of the argument are written to the stream. writeChar also takes an int argument.


Say that out is a DataOutputStream. How many bytes will the following write?

out.writeBoolean( true );
out.writeBoolean( false );

(Look at the documentation before answering.)