Professional Documents
Culture Documents
Java I/O (Input and Output) is used to process the input and produce the output
based on the input.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
java.io Package
Java.io package provides classes for system input and output through data
streams, serialization and the file system.
The java.io package contains nearly every class you might ever need to perform
input and output (I/O) in Java.
The InputStream class provides many different subclasses to read different kind
of input data from a source and the OutputStream class provides many different
subclasses to write different kind of output to a destination.
Java provides strong but flexible support for I/O related to Files and networks.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called
a stream because it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached
with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
System.out.println("simple message");
System.err.println("error message");
OutputStream
InputStream
Java application uses an input stream to read data from a source, it may be a
file,an array,peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given
below.
OutputStream class
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though
there are many classes related to byte streams but the most frequently used
classes are ,FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an input
file into an output file:
import java.io.*;
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in
creating output.txt file with the same content as we have in input.txt. So
let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
Character Streams
Java Character streams are used to perform input and output for 16-bit
unicode. Though there are many classes related to character streams but the
most frequently used classes are ,FileReader and FileWriter.
We can re-write above example which makes use of these two classes to copy an
input file (having unicode characters) into an output file:
import java.io.*;
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in
creating output.txt file with the same content as we have in input.txt. So
let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's
program can take input from a keyboard and then produce output on the
computer screen.
If you are aware if C or C++ programming languages, then you must be aware of
three standard devices STDIN, STDOUT and STDERR. Similar way Java provides
following three standard streams
Standard Input: This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's
program and usually a computer screen is used to standard output stream and
represented as System.out.
Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error stream and
represented as System.err.
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
This program continues reading and outputting same character until we press
'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
File Class
Reading and Writing Files:
FileInputStream:
This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.
Following constructor takes a file name as a string to create an input
stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object
to read the file. First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Methods of InputStream:
SN Methods with Description
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
The above code would create file test.txt and would write given numbers in binary
format. Same would be output on the stdout screen.
Example of Reading the data of current java file and writing it into another file
We can read the data of any file using the FileInputStream class whether
it is java file, image file, video file etc. In this example, we are reading the
data of C.java file and writing it into another file M.java.
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
Directories in Java:
A directory is a File which can contains a list of other files and directories. You
use File object to create directories, to list down files available in a directory.
Creating Directories:
There are two useful File utility methods, which can be used to create
directories:
The mkdir( ) method creates a directory, returning true on success and
false on failure. Failure indicates that the path specified in the File
object already exists, or that the directory cannot be created because
the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the
directory.
Listing Directories:
You can use list( ) method provided by File object to list down all the files
and directories available in a directory as follows:
import java.io.File;
try{
// create new file object
file = new File("/tmp");
PrintWriter Class
Class constructors
S.N. Constructor & Description
1 PrintWriter(File file)
This creates a new PrintWriter, without automatic line flushing, with
the specified file.
3 PrintWriter(OutputStream out)
This creates a new PrintWriter, without automatic line flushing, from
an existing OutputStream.
7 PrintWriter(Writer out)
This creates a new PrintWriter, without automatic line flushing.
Class methods
S.N. Method & Description
1 PrintWriter append(char c)
This method appends the specified character to this writer.
4 boolean checkError()
This method flushes the stream if it's not closed and checks its error state.
6 void close()
This method Closes the stream and releases any system resources
associated with it.
7 void flush()
This method Flushes the stream.
11 void print(char c)
This method prints a character.
12 void print(char[] s)
This method Prints an array of characters.
13 void print(double d)
This method Prints a double-precision floating-point number.
14 void print(float f)
This method prints a floating-point number.
15 void print(int i)
This method prints an integer.
16 void print(long l)
This method prints a long integer.
18 void print(String s)
This method prints a string.
21 void println()
This method terminates the current line by writing the line separator string.
22 void println(boolean x)
This method prints a boolean value and then terminates the line.
23 void println(char x)
This method prints a character and then terminates the line.
24 void println(char[] x)
This method prints an array of characters and then terminates the line.
25 void println(double x)
This method prints a double-precision floating-point number and then
terminates the line.
26 void println(float x)
This method prints a floating-point number and then terminates the line.
27 void println(int x)
This method prints an integer and then terminates the line.
28 void println(long x)
This method prints a long integer and then terminates the line.
29 void println(Object x)
This method prints an Object and then terminates the line.
30 void println(String x)
This method prints a String and then terminates the line.
34 void write(int c)
This methodWrites a single character.
35 void write(String s)
This method writes a string.
When an instance variable is declared as transient, then its value need not
persist when an object is stored. For example:
Class T {
transient int a; //will not persist
int b; //will persist
}
Here, if an object of type T is written to a persistent storage area, the contents
of a would not be saved, but the contents of b would.
The volatile modifier tells the compiler that the variable modified
by volatile can be changed unexpectedly by other parts of your program.
RandomAccessFile
The RandomAccessFile class in the Java IO API allows you to move around a file
and read from it or write to it as you need.
You can replace existing parts of a file too. This is not possible with
the FileInputStream or FileOutputStream.
Creating a RandomAccessFile
Before you can work with the RandomAccessFile class you must
instantiate it. Here is how that looks:
RandomAccessFile file =
new RandomAccessFile("c:\\data\\file.txt", "rw");
Notice the second input parameter to the constructor: "rw". This is the
mode you want to open file in. "rw" means read/write mode. Check the
JavaDoc for more details about what modes you can open
aRandomAccessFile in.
The read() method reads the byte located a the position in the file currently
pointed to by the file pointer.
Writing to a RandomAccessFile
Writing to a RandomAccessFile can be done using one it its
many write() methods. Here is a simple example:
RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt",
"rw");
file.write("Hello World".getBytes());
file.close();
Just like with the read() method the write() method advances the file
pointer after being called. That way you don't have to constantly move the
file pointer to write data to a new location in the file.
1 void close()
This method Closes this random access file stream and releases any system
resources associated with the stream.
2 FileChannel getChannel()
This method returns the unique FileChannel object associated with this file.
3 FileDescriptor getFD()
This method returns the opaque file descriptor object associated with this
stream.
4 long getFilePointer()
This method returns the current offset in this file.
5 long length()
This method returns the length of this file.
6 int read()
This method reads a byte of data from this file.
7 int read(byte[] b)
This method reads up to b.length bytes of data from this file into an array
of bytes.
9 boolean readBoolean()
This method reads a boolean from this file.
10 byte readByte()
This method reads a signed eight-bit value from this file.
11 char readChar()
This method reads a character from this file.
12 double readDouble()
This method reads a double from this file.
13 float readFloat()
This method reads a float from this file.
14 void readFully(byte[] b)
This method reads b.length bytes from this file into the byte array, starting
at the current file pointer.
16 int readInt()
This method reads a signed 32-bit integer from this file.
17 String readLine()
This method reads the next line of text from this file.
18 long readLong()
This method reads a signed 64-bit integer from this file.
19 short readShort()
This method reads a signed 16-bit number from this file.
20 int readUnsignedByte()
This method reads an unsigned eight-bit number from this file.
21 int readUnsignedShort()
This method reads an unsigned 16-bit number from this file.
22 String readUTF()
This method reads in a string from this file.
25 int skipBytes(int n)
This method attempts to skip over n bytes of input discarding the skipped
bytes.
26 void write(byte[] b)
This method writes b.length bytes from the specified byte array to this file,
starting at the current file pointer.
28 void write(int b)
This method writes the specified byte to this file.
29 void writeBoolean(boolean v)
This method writes a boolean to the file as a one-byte value.
30 void writeByte(int v)
This method writes a byte to the file as a one-byte value.
31 void writeBytes(String s)
This method writes the string to the file as a sequence of bytes.
32 void writeChar(int v)
This method writes a char to the file as a two-byte value, high byte first.
33 void writeChars(String s)
This method writes a string to the file as a sequence of characters.
34 void writeDouble(double v)
This method converts the double argument to a long using the
doubleToLongBits method in class Double, and then writes that long value
to the file as an eight-byte quantity, high byte first.
35 void writeFloat(float v)
This method 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.
36 void writeInt(int v)
This method writes an int to the file as four bytes, high byte first.
37 void writeLong(long v)
This method writes a long to the file as eight bytes, high byte first.
38 void writeShort(int v)
This method writes a short to the file as two bytes, high byte first.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Introduction to MultiThreading
Java provides built-in support for multithreaded programming. A multithreaded
program contains two or more parts that can run concurrently. Each part of such
a program is called a thread, and each thread defines a separate path of
execution.
Thus, multithreading is a specialized form of multitasking.
4. Dead state – A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever run
again.
Creating a Thread
In the most general sense, you create a thread by instantiating an object
of type Thread.
Java defines two ways in which this can be accomplished:
1. You can implement the Runnable interface.
2. You can extend the Thread class, itself.
1. Implementing Runnable:
The easiest way to create a thread is to create a class that implements the
Runnable interface.
Runnable abstracts a unit of executable code. You can construct a thread
on any object that implements Runnable.
To implement Runnable, a class need only implement a single method
called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread.
It is important to understand that run( ) can call other methods, use other
classes, and declare variables, just like the main thread can.
The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within your program. This thread will end
when run( ) returns.
After you create a class that implements Runnable, you will instantiate an
object of type Thread from within that class. Thread defines several
constructors.
The one that we will use is shown here:
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the
Runnable interface. The name of the new
thread is specified by threadName.
After the new thread is created, it will not start running until you call its
start( ) method, which is declared within Thread. In essence, start( )
executes a call to run( ).
2. Extending Thread
The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class.
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Thread Priorities
Thread priorities are used by the thread scheduler to decide when each
thread should be allowed to run. In theory, higher-priority threads get
more CPU time than lower-priority
threads.
To set a thread’s priority, use the setPriority( ) method, which is a member
of Thread. This is its general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and
MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to default
priority, specify
NORM_PRIORITY, which is currently 5. These priorities are defined
as final variables within Thread.
You can obtain the current priority setting by calling the getPriority( )
method of Thread, shown here:
final int getPriority( )
Example:
class clicker implements Runnable {
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
Synchronization
“When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a
time. The process by which this is achieved is called synchronization.”
Key to synchronization is the concept of the monitor (also called a
semaphore).
A monitor is an object that is used as a mutually exclusive lock, or mutex.
Only one thread can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the monitor. All
other threads attempting to enter the locked monitor will be suspended
until the first thread exits the monitor. These other threads are said to be
waiting for the monitor. A thread that owns a monitor can reenter the same
monitor if it so desires.
As you can see, by calling sleep( ), the call( ) method allows execution to
switch to another thread. This results in the mixed-up output of the three
message strings.
In this program, nothing exists to stop all three threads from calling the
same method, on the same object, at the same time. This is known as a
race condition, because the three threads are racing each other to
complete the method.
To fix the preceding program, you simply need to precede
call( )’s definition with the keyword synchronized, as shown here:
class Callme {
synchronized void call(String msg) {
This prevents other threads from entering call( ) while another thread is
using it.
After synchronized has been added to call( ), the output of the program
is as follows:
[Hello]
[Synchronized]
[World]
ThreadGroup
For both forms, groupName specifies the name of the thread group. The first
version creates a new group that has the current thread as its parent. In the
second form, the parent is specified by parentOb.
Daemon thread in java is a service provider thread that provides services to the
user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies,
JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage,
running threads etc.
If there is no user thread, why should JVM keep running this thread. That
is why JVM terminates the daemon thread if there is no user thread.
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output
daemon thread work
user thread work
user thread work