Java I/O (Input and Output) Is Used To Process The Input and Produce The
Java I/O (Input and Output) Is Used To Process The Input and Produce The
Java I/O (Input and Output) is used to process the input and produce the
output.
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.
Stream
A stream is a sequence of data. In Java a stream is composed of bytes. It's called a stream
because it is 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.
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 Hierarchy
InputStream Hierarchy
The Byte Stream Classes: Byte streams are defined by using two class hierarchies. At the top
are two abstract classes: InputStream and OutputStream. Each of these abstract classes has
several concrete subclasses that handle the differences between various devices, such as disk
files, network connections, and even memory buffers. The byte stream classes are shown in
Table 13-1.
The abstract classes InputStream and OutputStream define several key methods that the other
stream classes implement. Two of the most important are read( ) and write( ), which,
respectively, read and write bytes of data. Both methods are declared as abstract inside
InputStream and OutputStream. They are overridden by derived stream classes.
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is
being created. Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters. To obtain an
InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for
inputStream. Putting it all together, the following line of code creates a BufferedReader
that is connected to the keyboard:
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we
will be using is
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as
an integer value. It returns 1 when the end of the stream is encountered. As you can see,
it can throw an IOException.
This output may look a little different from what you expected, because System.in is line
buffered, by default. This means that no input is actually passed to the program until you press
ENTER. As you can guess, this does not make read( ) particularly valuable for interactive
console input.
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
import java.io.*;
class BRRead {
public static void main(String args[])throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
This method writes to the stream the byte specified by byteval. Although byteval is
declared as an integer, only the low-order eight bits are written. Here is a short example
that uses write( ) to output the character A followed by a newline to the screen:
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
PrintWriter defines several constructors. The one we will use is shown here:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Here, fileName specifies the name of the file that you want to open. When you create an
input stream, if the file does not exist, then FileNotFoundException is thrown. For
output streams, if the file cannot be created, then FileNotFoundException is thrown.
When an output file is opened, any preexisting file by the same name is destroyed. When
you are done with a file, you should close it by calling close( ). It is defined by both
FileInputStream and FileOutputStream, as shown here:
class ShowFile {
public static void main(String args[])throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream("Hello1.txt");
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
To write to a file, you can use the write( ) method defined by FileOutputStream. Its
simplest form is shown here:
void write(int byteval) throws IOException
This method writes the byte specified by byteval to the file. Although byteval is declared
as an integer, only the low-order eight bits are written to the file. If an error occurs during
writing, an IOException is thrown. The next example uses write( ) to copy a text file:
class CopyFile {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream("Hello.txt");
System.out.println();
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// open output file
try {
fout = new FileOutputStream("new.txt");
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}
// Copy File
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
Volatile & Transient Modifier:
When a field is declared volatile, the compiler and runtime are put on notice that this
variable is shared and that operations on it should not be reordered with other memory
operations. Volatile variables are not cached in registers or in caches where they are
hidden from other processors, so a read of a volatile variable always returns the most
recent write by any thread.
Java transient keyword is used in serialization. If you define any data member
as transient, it will not be serialized. When an instance variable is declared as
transient, then its value need not persist when an object is stored. For
example:
import java.io.*;
class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
import java.io.*;
class DePersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name+" "+s.age);
in.close();
}
}
211 ravi 0
interface Printable{ }
class A implements Printable{
public void a(){ System.out.println("a method"); }
}
class B implements Printable{
public void b(){ System.out.println("b method"); }
}
class Call{
void invoke(Printable p){//upcasting
if(p instanceof A){
A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
B b=(B)p;//Downcasting
b.b();
}
}
}//end of Call class
class Test4{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
}
}
Output: b method
Java Strictfp Keyword
Java strictfp keyword ensures that you will get the same result on every platform if
you perform operations in the floating-point variable. The precision may differ
from platform to platform that is why java programming language have provided
the strictfp keyword, so that you get same result on every platform. So, now you
have better control over the floating-point arithmetic.
When working with overloaded constructors, it is sometimes useful for one constructor to invoke
another. In Java, this is accomplished by using another form of the this keyword. The general
form is shown here:
this(arg-list);
When this( ) is executed, the overloaded constructor that matches the parameter list specified by
arg-list is executed first. Then, if there are any statements inside the original constructor, they are
executed. The call to this( ) must be the first statement within the constructor. To understand
how this( ) can be used, lets work through a short example. First, consider the following class
that does not use this( ):
class MyClass {
int a;
int b;
// initialize a and b individually
MyClass(int i, int j) {
a = i;
b = j;
}
// initialize a and b to the same value
MyClass(int i) {
a = i;
b = i;
}
// give a and b default values of 0
MyClass( ) {
a = 0;
b = 0;
}
}
This class contains three constructors, each of which initializes the values of a and b. The first is
passed individual values for a and b. The second is passed just one value, which is assigned to
both a and b. The third gives a and b default values of zero. By using this( ), it is possible to
rewrite MyClass as shown here:
class MyClass {
int a;
int b;
// initialize a and b individually
MyClass(int i, int j) {
a = i;
b = j;
}
// initialize a and b to the same value
MyClass(int i) {
this(i, i); // invokes MyClass(i, i)
}
// give a and b default values of 0
MyClass( ) {
this(0); // invokes MyClass(0)
}
}
In this version of MyClass, the only constructor that actually assigns values to the a and b fields
is MyClass(int, int). The other two constructors simply invoke that constructor (either directly
or indirectly) through this( ). For example, consider what happens when this statement executes:
MyClass mc = new MyClass(8);
The call to MyClass(8) causes this(8, 8) to be executed, which translates into a call to
MyClass(8, 8), because this is the version of the MyClass constructor whose parameter list
matches the arguments passed via this( ). Now, consider the following statement, which uses the
default constructor:
MyClass mc2 = new MyClass();
In this case, this(0) is called. This causes MyClass(0) to be invoked because it is the constructor
with the matching parameter list. Of course, MyClass(0) then calls MyClass(0, 0) as just
described. One reason why invoking overloaded constructors through this( ) can be useful is that
it can prevent the unnecessary duplication of code. In many cases, reducing duplicate code
decreases the time it takes to load your class because often the object code is smaller. This is
especially important for programs delivered via the Internet in which load times are an issue.
Using this( ) can also help structure your code when constructors contain a large amount of
duplicate code.