Java Reference
In-Depth Information
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java Stuff").resolve("MyFile.txt");
// Make sure we have a directory...
try(BufferedInputStream in =
new BufferedInputStream(Files.newInputStream(file))){
// read the file...
} catch(IOException e) {
e.printStackTrace();
}
The first argument to the
newInputStream()
method is the path to the file. You can supply optional ar-
guments following the first to specify the open options to be in effect when the file is opened. These are the
options from the
java.nio.file.StandardOpenOption
enumeration that you saw in the previous chapter.
The
newInputStream()
method assumes the
READ
open option if you do not specify any options. The meth-
od can throw the following exceptions:
•
IllegalArgumentException
if you specify an invalid combination of options
•
UnsupportedOperationException
if you specify an option that is not supported
•
IOException
if an I/O error occurs while opening the file
•
SecurityException
if the installed security manager determines that you are not permitted to
read the file
Wrapping the
InputStream
object that the method returns in a
java.io.BufferedInputStream
object
provides more efficient read operations. The stream has an internal buffer of a default size that is automat-
ically filled by reading from the file as you read from the buffered stream. You can create a
BufferedIn-
putStream
object with a buffer of a given size by specifying a second argument to the constructor of type
int
that determines the capacity of the stream buffer in bytes.
Buffered Stream Read Operations
You have two methods that read from a buffered input stream:
•
read()
reads a single byte from the stream buffer and returns it as a value of type
int
. If the end-
of-file (EOF) is reached, the method returns −1.
•
read(byte[] bytes, int offset, int length)
reads up to
length
bytes from the stream and
stores them in the
bytes
array starting at index position
offset
. Less than
length
bytes are read
if there are fewer than this number of bytes available up to end-of-file. The method returns the ac-
tual number of bytes read as type
int
or −1 if no bytes were read because EOF was reached. The
method throws a
NullPointerException
if the first argument is null and an
IndexOutOfBound-
sException
if
offset
or
length
are invalid or if the
bytes.length-offset
is less than
length
.
Both methods throw an
IOException
if the stream has been closed or if an I/O error occurs.
You can skip over a given number of bytes in the file by calling the
skip()
method for the stream object.
You specify the number of bytes that you want to skip as an argument of type
long
. The method returns the
actual number of bytes skipped as a
long
value. The method throws an
IOException
if an I/O error occurs
or if the underlying stream does not support seek, which means when
mark()
and
reset()
operations are
not supported.