Explain I/O streams in Java in detail.[2065,2064]
Ans:
InputStream class is an abstract base class which do provides the minimal programming interface and partial implementation of the input streams in Java. The InputStream defines the methods to read bytes or the arrays of bytes, marking the locations in stream, skipping the bytes of input, finding out the number of bytes which are available for reading, and resetting current position within the stream. The input stream is automatically opened when we create it. we can explicitly close the stream with the method close(), or let it be closed implicitly when a object is garbage collected.
OutputStream class is the abstract base class which provides minimal programming interface and the partial implementation of the output stream in Java. the OutputStream defines methods for writing the bytes or arrays of bytes to stream and flushing the stream. The output stream is automatically opened when we create it. We can explicitly close the output stream using close() method, or let it be closed implicitly when an object is garbage collected.
I/O Streams
Byte Streams handle I/O of raw binary data.
Character Streams handle I/O of character data, automatically handling translation to and from the local character set.
Buffered Streams optimize input and output by reducing the number of calls to the native API.
Scanning and Formatting allows a program to read and write formatted text.
I/O from the Command Line describes the Standard Streams and the Console object.
Data Streams handle binary I/O of primitive data type and String values.
Object Streams handle binary I/O of objects.
Console I/O Stream
Stream Tokenized[2060]
A stream tokenizer takes an input stream and parses it into tokens, allowing the tokens to be read one at a time.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class StreamTokenApp {
public static void main(String args[]) throws IOException {
BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer inStream = new StreamTokenizer(inData);
inStream.commentChar('#');
boolean eof = false;
do {
int token = inStream.nextToken();
switch (token) {
case inStream.TT_EOF:
System.out.println("EOF encountered.");
eof = true;
break;
case inStream.TT_EOL:
System.out.println("EOL encountered.");
break;
case inStream.TT_WORD:
System.out.println("Word: " + inStream.sval);
break;
case inStream.TT_NUMBER:
System.out.println("Number: " + inStream.nval);
break;
default:
System.out.println((char) token + " encountered.");
if (token == '!')
eof = true;
}
} while (!eof);
}
}
Console I/O stream:
a. InputStrem:-
It is used to store the information about the connection between an input devices and computer program.
b. InputStreamReader:-
It is used to translate data bytes received from InputStream Object in to a stream of character. To obtain InputStreamReader object that is linked to system.in.
c. BufferedReader:-
It is used to buffer(store) the input received from InputStreamReader.
To take input From Keyboard
import java.io.*;
public class IODemo
{
public static void main(String args[])
{
int a=0,b=0,sum=0;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter two number");
try
{
a=Integer.parseInt(br.ReadLine());
b=Integer.parseInt(br.ReadLine());
}
catch(IOException ex)
{
System.out.println(ex);
}
sum =a+b;
System.out.println("Sum="+sum);
}
}
To take Input frm File
import java.io.*;
class FileInputDemo
{
public static void main(String args[])
{
String Text,filename=" ";
try
{
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader kbr =new BufferedReader(isr);
System.out.println("Enter File name");
filename=kbr.Readline;
FileReader fr= new FileReader("File name");
BufferedReader br =new BufferedReader(fr);
while(Text =br.ReadLine())!=null)
{
System.out.println(Text);
}
}
catch(FileNotFoundException ex)
{
System.out.println(ex);
}
catch(IOException ee)
{
System.out.println(ee);
}
}
}
To Write in file
import java.io.*;
class FileOutDemo
{
public static void main(String args[])
{
try
{
String text="Welcome",filename=" ";
{
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader kbr =new BufferedReader(isr);
System.out.println("Enter File name");
filename=kbr.ReadLine();
FileOutputStream fos =new FileOutputStream(filename);
PrintStream Ps= new PrintStream (fos);
Ps.priintln(text);
}
catch(IOException ex)
{
System.out.println(ex);
}
}
}
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream(File filename);
Reading Text from the Standard Input
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader inp = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}
To read and write to the command prompt console:
import java.io.*;
public class ReadStringFromConsole {
public static void main (String[] args) {
System.out.print("Prompt: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strInput = null;
try {
strInput = br.readLine();
} catch (IOException ioe) {
System.out.println("Error trying to read input.");
System.exit(1);
}
System.out.println("Thank you, " + strInput );
} // end of main.
} // end of ReadStringFromConsole class
Java read file line by line
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
}
}
}
Java Write To File
import java.io.*;
public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File("textfile1.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not exist");
}
}
Create File in Java
import java.io.*;
public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created
to the current directory");
}
}
}
Ans:
InputStream class is an abstract base class which do provides the minimal programming interface and partial implementation of the input streams in Java. The InputStream defines the methods to read bytes or the arrays of bytes, marking the locations in stream, skipping the bytes of input, finding out the number of bytes which are available for reading, and resetting current position within the stream. The input stream is automatically opened when we create it. we can explicitly close the stream with the method close(), or let it be closed implicitly when a object is garbage collected.
OutputStream class is the abstract base class which provides minimal programming interface and the partial implementation of the output stream in Java. the OutputStream defines methods for writing the bytes or arrays of bytes to stream and flushing the stream. The output stream is automatically opened when we create it. We can explicitly close the output stream using close() method, or let it be closed implicitly when an object is garbage collected.
I/O Streams
Byte Streams handle I/O of raw binary data.
Character Streams handle I/O of character data, automatically handling translation to and from the local character set.
Buffered Streams optimize input and output by reducing the number of calls to the native API.
Scanning and Formatting allows a program to read and write formatted text.
I/O from the Command Line describes the Standard Streams and the Console object.
Data Streams handle binary I/O of primitive data type and String values.
Object Streams handle binary I/O of objects.
Console I/O Stream
Stream Tokenized[2060]
A stream tokenizer takes an input stream and parses it into tokens, allowing the tokens to be read one at a time.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class StreamTokenApp {
public static void main(String args[]) throws IOException {
BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer inStream = new StreamTokenizer(inData);
inStream.commentChar('#');
boolean eof = false;
do {
int token = inStream.nextToken();
switch (token) {
case inStream.TT_EOF:
System.out.println("EOF encountered.");
eof = true;
break;
case inStream.TT_EOL:
System.out.println("EOL encountered.");
break;
case inStream.TT_WORD:
System.out.println("Word: " + inStream.sval);
break;
case inStream.TT_NUMBER:
System.out.println("Number: " + inStream.nval);
break;
default:
System.out.println((char) token + " encountered.");
if (token == '!')
eof = true;
}
} while (!eof);
}
}
Console I/O stream:
a. InputStrem:-
It is used to store the information about the connection between an input devices and computer program.
b. InputStreamReader:-
It is used to translate data bytes received from InputStream Object in to a stream of character. To obtain InputStreamReader object that is linked to system.in.
c. BufferedReader:-
It is used to buffer(store) the input received from InputStreamReader.
To take input From Keyboard
import java.io.*;
public class IODemo
{
public static void main(String args[])
{
int a=0,b=0,sum=0;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter two number");
try
{
a=Integer.parseInt(br.ReadLine());
b=Integer.parseInt(br.ReadLine());
}
catch(IOException ex)
{
System.out.println(ex);
}
sum =a+b;
System.out.println("Sum="+sum);
}
}
To take Input frm File
import java.io.*;
class FileInputDemo
{
public static void main(String args[])
{
String Text,filename=" ";
try
{
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader kbr =new BufferedReader(isr);
System.out.println("Enter File name");
filename=kbr.Readline;
FileReader fr= new FileReader("File name");
BufferedReader br =new BufferedReader(fr);
while(Text =br.ReadLine())!=null)
{
System.out.println(Text);
}
}
catch(FileNotFoundException ex)
{
System.out.println(ex);
}
catch(IOException ee)
{
System.out.println(ee);
}
}
}
To Write in file
import java.io.*;
class FileOutDemo
{
public static void main(String args[])
{
try
{
String text="Welcome",filename=" ";
{
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader kbr =new BufferedReader(isr);
System.out.println("Enter File name");
filename=kbr.ReadLine();
FileOutputStream fos =new FileOutputStream(filename);
PrintStream Ps= new PrintStream (fos);
Ps.priintln(text);
}
catch(IOException ex)
{
System.out.println(ex);
}
}
}
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream(File filename);
Reading Text from the Standard Input
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader inp = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}
To read and write to the command prompt console:
import java.io.*;
public class ReadStringFromConsole {
public static void main (String[] args) {
System.out.print("Prompt: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strInput = null;
try {
strInput = br.readLine();
} catch (IOException ioe) {
System.out.println("Error trying to read input.");
System.exit(1);
}
System.out.println("Thank you, " + strInput );
} // end of main.
} // end of ReadStringFromConsole class
Java read file line by line
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
}
}
}
Java Write To File
import java.io.*;
public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File("textfile1.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not exist");
}
}
Create File in Java
import java.io.*;
public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created
to the current directory");
}
}
}