Java Reference
In-Depth Information
The
available()
method for a
BufferedInputStream
returns an estimate of the number of bytes you
can read or skip over without blocking as a value of type
int
. A stream can be blocked if another thread of
execution is reading from the same file.
Marking a Stream
You can mark the current position in a buffered stream by calling
mark()
for the stream object. The ar-
gument to this method is an integer specifying the number of bytes that can be read or skipped before the
current mark is invalidated. You can return to the position in the stream that you have marked by calling the
reset()
method for the stream object. This enables you to read a section of a file repeatedly.
The
markSupported()
method for a
BufferedInputStream
object tests if the stream supports marking
the stream. It returns
true
if
mark()
and
reset()
are supported and
false
otherwise.
Let's try an example.
TRY IT OUT: Reading a Binary File
In this example, you read the
fibonacci.bin
file that you created in the
Junk
directory in the previous
chapter.
import java.nio.file.*;
import java.nio.*;
import java.io.*;
public class StreamInputFromFile {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("fibonnaci.bin");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating
program.");
System.exit(1);
}
final int count = 6;
// Number of values
to be read each time
// Buffer to hold count values
ByteBuffer buf = ByteBuffer.allocate(8*count);
LongBuffer values = buf.asLongBuffer();
byte[] bytes = buf.array();
// Backing array for
buf
int totalRead = 0;
// Total value read