O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Miscellaneous Methods

The DataInputStream and DataOutputStream classes each have one method left to discuss, skipBytes() and size(), respectively.

Determining the Number of Bytes Written

The DataOutputStream class has a protected field called written that stores the number of bytes written to the output stream since it was constructed. The value of this field is returned by the public size() method:

protected int written
public final int size()

Every time you invoke writeInt(), writeBytes(), writeUTF(), or some other write method, the written field is incremented by the number of bytes written. This might be useful if for some reason you’re trying to limit the number of bytes you write. For instance, you may prefer to open a new file when you reach some preset size rather than continuing to write into a very large file.

Skipping Bytes in an Input Stream

The DataInputStream class’s skipBytes() method skips over a specified number of bytes without reading them. Unlike the skip() method of java.io.InputStream that DataInputStream inherits, skipBytes() either skips over all the bytes it’s asked to skip or it throws an exception:

public final int skipBytes(int n) throws IOException
public long skip(long n) throws IOException

skipBytes() blocks and waits for more data until n bytes have been skipped (successful execution) or an exception is thrown. The method returns the number of bytes skipped, which is always n (because if it’s not n , an exception is thrown and nothing is returned). On ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required