0% found this document useful (0 votes)
41 views11 pages

Java Binary I/O Classes Overview

Uploaded by

Subrahmanya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views11 pages

Java Binary I/O Classes Overview

Uploaded by

Subrahmanya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

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

[Link]
The value returned is a
+read(): int
byte as an int type
+read(b: byte[]): int

+read(b: byte[], off: int,len:


int): int
+available(): int
+close(): void
+skip(n: long): long

+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 [Link] 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 [Link] 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
[Link] 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.

The FileInputStream class


To construct a FileInputStreamobject, usethe following constructors
public FileInputStream(String filename)
public FileInputStream(File file)
A [Link] if you attempt to create a FileInputStreamwith a
nonexistent file

The FileInputStream class


JAVA PROGRAMMING
To construct a FileOutputStreamobject, use the followingconstructors
public FileOutputStream(String filename)
public FileOutputStream(File file)
public FileOutputStream(String filename, boolean append)
public FileOutputStream(File file, boolean append)
If the file does not exist, a new file will be created
If the file already exists, the first two constructors will delete the current contents in the
file.
To retain the current content and append new data into thefile, use the last two
constructors by passing true to the append parameter

Binary file I/O using FileInputStream and FileOutputStream


public class TestFileStream
{
public static void main(String[] args) throws IOException
{
try (
FileOutputStream output = new FileOutputStream("[Link]");
)
{
for( int i=0; i<=10; i++)
[Link](i);
}
try (
{
FileInputStream input = new FileInputStream ("[Link]");
) {
int value;
While((value == [Link]()) != -1)
[Link](value + “ ”);
}
}
}
Filter Stream

FileInputStreamprovides a readmethodthat can only be used for reading bytes


If you want to read integers, doubles, or strings,you need a filter class to wrap the
byte input stream
Filter streams are streams that filter bytes forsome purpose
Using a filter class enables you to read integers,doubles, and strings instead of bytes
and characters
JAVA PROGRAMMING

The DataInputStream Class

DataInputStream reads bytes from the stream and convertsthem into appropriate primitive
type values or strings.

DataInputStream extends FilterInputStream andimplements the DataInputinterface.

The DataOutputStream Class

DataOutputStreamconverts primitive type values or strings into bytes and output the bytes
to the stream.

DataOutputStreamextends FilterOutputStreamand implements the


DataOutputinterface
JAVA PROGRAMMING

Character and String in Binary I/O

Remember, a Unicode character consists of two bytes


 The writeChar(char c)method writes the Unicode ofcharacter cto the output.
 The writeChars(String s)method writes the Unicode for each character in the string s
to the output

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)

Unicode Transformation Format (UTF)


 The writeUTF(String s)method writes thestring sin UTF
 UTF is coding scheme for efficiently compressing astring of Unicode characters

Binary file I/O using DataInputStream and DataOutputStream

public class TestDataStream {


public static void main(String[]
args) throws IOException {try (
// Create an output stream for
file [Link]
DataOutputStream output =
new DataOutputStream(new FileOutputStream("[Link]"));
) {
[Link]("John");
[Link](85.5);
[Link]("Jim");
[Link](185.5);
[Link]("George");
[Link](105.25);
}
try (
DataInputStream input = new DataInputStream(new
FileInputStream("[Link]"));
) {
[Link]([Link]() + " " + [Link]());
JAVA PROGRAMMING
[Link]([Link]() + " " + [Link]());
[Link]([Link]() + " " + [Link]());
}
}
}

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("[Link]"))) {while (true)
[Link]([Link]());
}
}
Use [Link]() tocheck for
catch (EOFException ex) {
EOF (if [Link]() == 0,
[Link]("All data were read");
then it is EOF)
}
catch (IOException ex) {
[Link]();
}
}

Binary Filter I/O Classes


Use BufferedInputStream and BufferedOutputStream tospeed up input and output by reading
ahead and writing later.
All the methods in BufferedInputStream and
BufferedOutputStreamare inherited from their superclasses

The BufferedInputStream and BufferedOutputStream Classes

// 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

Modifier and Method Method


Type
void close() It closes this random access file stream and releases any
system resources associated with the stream.
FileChannel getChannel() It returns the unique FileChannel
object associated with this file.
int readInt() It reads a signed 32-bit integer from this file.
String readUTF() It reads in a string from this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning
of this file, at which the next read or write occurs.
void writeDouble(double It converts the double argument to a long using the
v) doubleToLongBits method in class Double, and then writes
that long value to the file as an eight-byte quantity, high
byte first.
JAVA PROGRAMMING
void writeFloat(float v) It converts the float argument to an int using the
floatToIntBits method in class Float, and then writes that int
value to the file as a four-byte quantity, high byte first.
void write(int b) It writes the specified byte to this file.
int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning
of this file, at which the next read or write occurs.

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.

Thread Life Cycle and Methods


A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.

 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

Common questions

Powered by AI

The FileInputStream and FileOutputStream classes in Java are used to handle file streams for binary data I/O operations. FileInputStream reads bytes from a file specified by a filename or a File object, and raises a FileNotFoundException if the file does not exist. FileOutputStream can write bytes to a file, creating a new file if needed, and supports overwriting or appending data based on the constructor used. These classes allow direct handling of files as byte streams, essential for non-text data, while also managing exceptions related to file handling .

DataInputStream and DataOutputStream are specialized classes in Java that extend FilterInputStream and FilterOutputStream to handle primitive data types and strings. DataInputStream reads bytes and converts them into appropriate primitive type values or strings, while DataOutputStream converts primitive types or strings into bytes and writes them to the stream. These streams are beneficial because they abstract the process of byte conversion, allowing developers to read and write complex data types beyond simple bytes, thereby simplifying data processing tasks .

Multithreading in Java improves resource utilization by allowing multiple threads to execute concurrently within a single program, thus efficiently utilizing CPU resources. In a multi-threading scenario, different parts of the program can handle separate tasks simultaneously. This reduces idle time and enhances performance, especially on multi-core processors, by ensuring that CPU cycles are always directed towards productive tasks. The OS efficiently manages time slicing among threads within an application, promoting faster and more responsive program behavior .

To write and read integers, doubles, and strings from a binary file using Java's I/O, the following steps should be followed: first, use DataOutputStream to encapsulate a FileOutputStream and employ its write methods (e.g., writeInt, writeDouble, writeUTF) to write respective data types to a file. Then, create a DataInputStream wrapping a FileInputStream to read the binary data using corresponding read methods (e.g., readInt, readDouble, readUTF). Finally, handle any required exceptions such as IOException to ensure robustness during file operations .

Handling EOFException in Java occurs when reading past the end of an InputStream with DataInputStream. The recommended steps are: first, encapsulate the I/O operations within a try block; second, read data within a loop until EOFException is thrown, indicating the end of the file; and third, catch the EOFException separately to perform end-of-file logic, such as printing a message that all data has been read. Additional catch blocks should handle any IOException instances, ensuring robust error management throughout the process .

Binary I/O in Java is more efficient than text I/O because it does not involve encoding or decoding processes. In binary I/O, the original bytes are directly written to or read from a file, meaning the exact byte is processed without any conversion to a different encoding format. This contrasts with text I/O, where characters are typically converted to and from Unicode, adding an additional processing step that affects performance .

BufferedInputStream and BufferedOutputStream are used in Java to enhance the performance of I/O operations by temporarily storing data in buffer blocks. This reduces the number of I/O operations by enabling large chunks of data to be read or written in a single operation instead of byte-by-byte processing. The buffering mechanism reduces the overhead of I/O calls, thus speeding up data transfer for applications that handle large volumes of data in files or network streams .

RandomAccessFile is used in scenarios where non-sequential access to file data is required, as it allows direct read and write operations at any byte position in the file. This behavior is akin to an array of bytes, where a file pointer moves to designated positions to perform operations. RandomAccessFile supports methods like 'seek()', 'readInt()', 'writeDouble()', allowing developers to read and write primitive data types and strings at specific file offsets. This makes it ideal for applications like database systems and file-based indexing where fast, direct data access is critical .

The InputStream and OutputStream classes are the root classes for reading and writing binary data in Java, respectively. InputStream provides methods like 'read()', which reads bytes of data, and 'available()', which returns the number of bytes that can be read. OutputStream offers methods like 'write()', which writes bytes to the stream, and 'flush()', ensuring that any buffered output bytes are written out. These methods facilitate efficient and effective binary data manipulation by allowing fine control over the reading and writing processes .

Java manages the thread lifecycle through various states: New, Runnable, Waiting, Timed Waiting, and Terminated. A thread starts in the 'New' state, transitions to 'Runnable' when started, enters 'Waiting' if it awaits another thread's action, and 'Timed Waiting' if waiting for a specific period. Finally, it goes to 'Terminated' after execution. Managing these states is crucial for concurrent programming, as it involves synchronizing threads to ensure correct sequencing and optimal resource usage. Proper handling minimizes concurrency issues such as deadlocks or race conditions, ensuring efficient multithreading operations .

You might also like