Java Chapter 4 Notes
Java Chapter 4 Notes
CHAPTER 4
I/O Programming
FILES
1. Files can be classified as either text or binary
Human readable files are text files
All other files are binary files
2. Java provides many classes for performing textI/O and binary I/O
Remember, a Fileobject encapsulates the properties of afile or a path, but does not
contain the methods for reading/writing data from/to a file
In order to perform I/O, you need to create objects usingappropriate Java I/O classes
The objects contain the methods for reading/writing datafrom/to a file
Text I/O
Use the Scannerclass for reading text data from a file
The JVM converts a file specific encoding when to Unicode when reading a character
Use the PrintWriter class for writing text data to a file
The JVM converts Unicode to a file specific encoding when writing acharacter
BINARY I/O
Binary I/O does not involve encoding or decodingand thus is more efficient than text I/O
Binary files are independent of the encodingscheme on the host machine
When you write a byte to a file, the original byte is copied into the file. When you read a
byte from a file, theexact byte in the file is returned.
The abstract InputStream is the root class forreading binary data
JAVA PROGRAMMING
The abstract OutputStream is the root class forwriting binary data
The InputStreamclass
java.io.InputStream
The value returned is a
+read(): int
byte as an int type
+read(b: byte[]): int
+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void
Reads the next byte of data from the input stream. The value byte is returned asan
int value in the range 0 to 255. If no byte is available because the end of the stream
has been reached, the value –1 is returned.
Reads up to b.length bytes into array b from the input stream and returns theactual
number of bytes read. Returns -1 at the end of the stream.
JAVA PROGRAMMING
Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len-1].
The actual number of bytes read is returned. Returns -1 at theend of the stream.
Returns the number of bytes that can be read from the input stream.
Closes this input stream and releases any system resources associated with the
stream.
Skips over and discards n bytes of data from this input stream. The actualnumber of
bytes skipped is returned.
Tests if this input stream supports the mark and reset methods.Marks the current
position in this input stream.
Repositions this stream to the position at the time the mark method was lastcalled
on this input stream.
The InputStreamclass
java.io.OutputStream The value is a byte as an int type
+write(int b): void Writes the specified byte to this output stream. The
parameter b is an int value (byte)b is written to the
+write(b: byte[]): void output stream.
+write(b: byte[], off: int, Writes all the bytes in array b to the output stream.
len: int): void Writes b[off], b[off+1],…, b[off+len-1] into the output
stream.
+close(): void
Closes this output stream and releases any system
+flush(): void resources associated with thestream.
Flushes this output stream and forces any buffered
output bytes to be written out.
DataInputStream reads bytes from the stream and convertsthem into appropriate primitive
type values or strings.
DataOutputStreamconverts primitive type values or strings into bytes and output the bytes
to the stream.
Remember, an ASCII character consists of one byte, whichis stored in the lower byte of a
Unicode character
The writeByte(int v)method writes the lowest byte ofinteger v to the output (i.e., the
higher three bytes of the integer are discarded)
The writeBytes(String s)method writes the lower byteof the Unicode of the
characters in the string s to the output (i.e., the higher byte of the Unicode of the
characters are discarded)
END OF FILE
If you keep reading data at the end of an InputStream, then an EOFException will occur
public class DetectEndOfFile {
public static void main(String[] args) {
try {
try (DataInputStream input =
new DataInputStream(new FileInputStream("test.dat"))) {while (true)
System.out.println(input.readDouble());
}
}
Use input.available() tocheck for
catch (EOFException ex) {
EOF (if input.available() == 0,
System.out.println("All data were read");
then it is EOF)
}
catch (IOException ex) {
ex.printStackTrace();
}
}
// Create a BufferedInputStream
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize) The default buffer
size is 512 bytes
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
JAVA PROGRAMMING
public BufferedOutputStream(OutputStream out, int bufferSize)
Objects
ObjectInputStream and ObjectOutputStream can be used to read andwrite serializable
objects
Random access
RandomAccessFile allows data to be read fromand written to any location (not
necessarily sequentially) in the file
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired
number of byte has been read than EOFException is thrown. It is a type of IOException.
Constructor Description
RandomAccessFile(File file, String Creates a random access file stream to read from, and
mode) optionally to write to, the file specified by the File argument.
RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.
Methods of RandomAccessFiles
Multithreading in Java
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the same time making optimal
use of the available resources especially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
JAVA PROGRAMMING
Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.
JAVA PROGRAMMING