Java Reference
In-Depth Information
Path references can be indicated in a manner specific to a platform, such as this example
to read a file on a Windows system:
FileInputStream f1 = new FileInputStream(“\\data\\calendar.txt”);
15
Because Java uses backslash characters in escape codes, the
code '\\' must be used in place of '\' in path references on
Windows.
NOTE
Here's a Linux example:
FileInputStream f2 = new FileInputStream(“/data/calendar.txt”);
A better way to refer to paths is to use the class variable separator in the File class,
which works on any operating system:
char sep = File.separator;
FileInputStream f2 = new FileInputStream(sep + “data”
+ sep + “calendar.txt”);
After you create a file input stream, you can read bytes from the stream by calling its
read() method. This method returns an integer containing the next byte in the stream. If
the method returns -1, which is not a possible byte value, this signifies that the end of
the file stream has been reached.
To read more than one byte of data from the stream, call its read( byte[] , int , int )
method. The arguments to this method are as follows:
1. A byte array where the data will be stored
2. The element inside the array where the data's first byte should be stored
3. The number of bytes to read
Unlike the other read() method, this does not return data from the stream. Instead, it
returns either an integer that represents the number of bytes read or -1 if no bytes were
read before the end of the stream was reached.
The following statements use a while loop to read the data in a FileInputStream object
called diskfile :
int newByte = 0;
while (newByte != -1) {
newByte = diskfile.read();
System.out.print(newByte + “ “);
}
Search WWH ::




Custom Search