0% found this document useful (0 votes)
56 views

Java Chapter 4 Notes

Uploaded by

Subrahmanya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Java Chapter 4 Notes

Uploaded by

Subrahmanya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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

java.io.InputStream
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 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.

The FileInputStream class


To construct a FileInputStreamobject, usethe following constructors
public FileInputStream(String filename)
public FileInputStream(File file)
A java.io.FileNotFoundExceptionwilloccur 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("temp.dat");
)
{
for( int i=0; i<=10; i++)
output.write(i);
}
try (
{
FileInputStream input = new FileInputStream ("temp.dat");
) {
int value;
While((value == input.read()) != -1)
System.out.print(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 temp.dat
DataOutputStream output =
new DataOutputStream(new FileOutputStream("temp.dat"));
) {
output.writeUTF("John");
output.writeDouble(85.5);
output.writeUTF("Jim");
output.writeDouble(185.5);
output.writeUTF("George");
output.writeDouble(105.25);
}
try (
DataInputStream input = new DataInputStream(new
FileInputStream("temp.dat"));
) {
System.out.println(input.readUTF() + " " + input.readDouble());
JAVA PROGRAMMING
System.out.println(input.readUTF() + " " + input.readDouble());
System.out.println(input.readUTF() + " " + input.readDouble());
}
}
}

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();
}
}

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

You might also like