SlideShare a Scribd company logo
JAVA INPUT/OUTPUT
BYLECTURERSURAJPANDEYCCTCOLLEGE
 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.
 We can perform file handling in java by java IO
API.
BYLECTURERSURAJPANDEYCCT
COLLEGE
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
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Let's see the code to print output and
error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st c
haracter
2. System.out.println((char)i);//will print the character
BYLECTURERSURAJPANDEYCCT
COLLEGE
 The java.io package contains nearly every class you
might ever need to perform input and output (I/O) in
Java. All these streams represent an input source and
an output destination. The stream in the java.io package
supports many data such as primitives, Object, localized
characters, etc.
 Stream
 A stream can be defined as a sequence of data. there
are two kinds of Streams
 InPutStream: The InputStream is used to read data
from a source.
 OutPutStream: the OutputStream is used for writing
data to a destination.
BYLECTURERSURAJPANDEYCCT
COLLEGE
LET'S UNDERSTAND WORKING OF JAVA OUTPUTSTREAM AND INPUTSTREAM BY THE
FIGURE GIVEN BELOW.
BYLECTURERSURAJPANDEYCCT
COLLEGE
OUTPUTSTREAM CLASS
 OutputStream class is an abstract class.It is the
superclass of all classes representing an output
stream of bytes. An output stream accepts output
bytes and sends them to some sink.
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
 InputStream class
 InputStream class is an abstract class.It is the
superclass of all classes representing an input
stream of bytes.
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
FILEINPUTSTREAM AND FILEOUTPUTSTREAM (FILE
HANDLING)
 In Java, FileInputStream and FileOutputStream
classes are used to read and write data in file. In
another words, they are used for file handling in
java.
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA FILEOUTPUTSTREAM CLASS
 Java FileOutputStream is an output stream for
writing data to a file.
 If you have to write primitive values then use
FileOutputStream.Instead, for character-oriented
data, prefer FileWriter.But you can write byte-
oriented as well as character-oriented data.
BYLECTURERSURAJPANDEYCCT
COLLEGE
EXAMPLE OF JAVA FILEOUTPUTSTREAM CLASS
 import java.io.*;
 class Test{
 public static void main(String args[]){
 try{
 FileOutputstream fout=new FileOutputStream("abc.txt");
 String s="Sachin Tendulkar is my favourite player";
 byte b[]=s.getBytes();//converting string into byte array
 fout.write(b);
 fout.close();
 System.out.println("success...");
 }catch(Exception e){system.out.println(e);}
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA FILEINPUTSTREAM CLASS
 Java FileInputStream class obtains input bytes from
a file.It is used for reading streams of raw bytes
such as image data. For reading streams of
characters, consider using FileReader.
 It should be used to read byte-oriented data for
example to read image, audio, video etc.
BYLECTURERSURAJPANDEYCCT
COLLEGE
EXAMPLE OF FILEINPUTSTREAM CLASS
 import java.io.*;
 class SimpleRead{
 public static void main(String args[]){
 try{
 FileInputStream fin=new FileInputStream("abc.txt");
 int i=0;
 while((i=fin.read())!=-1){
 System.out.println((char)i);
 }
 fin.close();
 }catch(Exception e){system.out.println(e);}
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Output:Sachin is my favourite player.
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
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.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class C{
 public static void main(String args[])throws Exception{
 FileInputStream fin=new FileInputStream("C.java");
 FileOutputStream fout=new FileOutputStream("M.java");
 int i=0;
 while((i=fin.read())!=-1){
 fout.write((byte)i);
 }
 fin.close();
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA BYTEARRAYOUTPUTSTREAM CLASS
 Java ByteArrayOutputStream class is used to write
data into multiple files. In this stream, the data is
written into a byte array that can be written to
multiple stream.
 The ByteArrayOutputStream holds a copy of data
and forwards it to multiple streams.
 The buffer of ByteArrayOutputStream automatically
grows according to data.
 Closing the ByteArrayOutputStream has no
effect.
BYLECTURERSURAJPANDEYCCT
COLLEGE
CONSTRUCTORS OF BYTEARRAYOUTPUTSTREAM
CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
METHODS OF BYTEARRAYOUTPUTSTREAM CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA BYTEARRAYOUTPUTSTREAM EXAMPLE
 Let's see a simple example of java
ByteArrayOutputStream class to write data into 2
files.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class S{
 public static void main(String args[])throws Exception{
 FileOutputStream fout1=new FileOutputStream("f1.txt");
 FileOutputStream fout2=new FileOutputStream("f2.txt");
 ByteArrayOutputStream bout=new ByteArrayOutputStream();
 bout.write(139);
 bout.writeTo(fout1);
 bout.writeTo(fout2);
 bout.flush();
 bout.close();//has no effect
 System.out.println("success...");
 }
 }
 success...
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA SEQUENCEINPUTSTREAM CLASS
 Java SequenceInputStream class is used to read
data from multiple streams. It reads data of streams
one by one.
BYLECTURERSURAJPANDEYCCT
COLLEGE
CONSTRUCTORS OF SEQUENCEINPUTSTREAM
CLASS:
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Constructors of SequenceInputStream class:
 Simple example of SequenceInputStream class
 In this example, we are printing the data of two files
f1.txt and f2.txt.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class Simple{
 public static void main(String args[])throws Exception{
 FileinputStream fin1=new FileinputStream("f1.txt");
 FileinputStream fin2=new FileinputStream("f2.txt");
 SequenceinputStream sis=new SequenceinputStream(fin1,fin2
);
 int i;
 while((i=sis.read())!=-1){
 System.out.println((char)i);
 }
 sis.close();
 fin1.close();
 fin2.close();
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
EXAMPLE OF SEQUENCEINPUTSTREAM THAT
READS THE DATA FROM TWO FILES
 In this example, we are writing the data of two files
f1.txt and f2.txt into another file named f3.txt.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 //reading data of 2 files and writing it into one file
 import java.io.*;
 class Simple{
 public static void main(String args[])throws Exception{
 FileinputStream fin1=new FileinputStream("f1.txt");
 FileinputStream fin2=new FileinputStream("f2.txt");
 FileOutputStream fout=new FileOutputStream("f3.txt");
 SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
 int i;
 while((i.sisread())!=-1)
 {
 fout.write(i);
 }
 sis.close();
 fout.close();
 fin.close();
 fin.close();
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
EXAMPLE OF SEQUENCEINPUTSTREAM CLASS THAT READS THE DATA
FROM MULTIPLE FILES USING ENUMERATION
 If we need to read the data from more than two
files, we need to have these information in the
Enumeration object. Enumeration object can be get
by calling elements method of the Vector class.
Let's see the simple example where we are reading
the data from the 4 files.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 import java.util.*;
 class B{
 public static void main(String args[])throws IOException{
 //creating the FileInputStream objects for all the files
 FileInputStream fin=new FileInputStream("A.java");
 FileInputStream fin2=new FileInputStream("abc2.txt");
 FileInputStream fin3=new FileInputStream("abc.txt");
 FileInputStream fin4=new FileInputStream("B.java");
 //creating Vector object to all the stream
 Vector v=new Vector();
 v.add(fin);
 v.add(fin2);
 v.add(fin3);
 v.add(fin4);
 //creating enumeration object by calling the elements method
 Enumeration e=v.elements();
 //passing the enumeration object in the constructor
 SequenceInputStream bin=new SequenceInputStream(e);
 int i=0;
 while((i=bin.read())!=-1){
 System.out.print((char)i);
 }
 bin.close();
 fin.close();
 fin2.close();
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA BUFFEREDOUTPUTSTREAM AND
BUFFEREDINPUTSTREAM
 Java BufferedOutputStream class
 Java BufferedOutputStream class uses an internal
buffer to store data. It adds more efficiency than to
write data directly into a stream. So, it makes the
performance fast.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Example of BufferedOutputStream class:
 In this example, we are writing the textual
information in the BufferedOutputStream object
which is connected to the FileOutputStream object.
The flush() flushes the data of one stream and send
it into another. It is required if you have connected
the one stream with another.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class Test{
 public static void main(String args[])throws Exception{
 FileOutputStream fout=new FileOutputStream("f1.txt");
 BufferedOutputStream bout=new BufferedOutputStream(fout);
 String s="Sachin is my favourite player";
 byte b[]=s.getBytes();
 bout.write(b);
 bout.flush();
 bout.close();
 fout.close();
 System.out.println("success");
 }
 }
 Output:
 success...
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA BUFFEREDINPUTSTREAM CLASS
 Java BufferedInputStream class is used to read
information from stream. It internally uses buffer
mechanism to make the performance fast.
 Example of Java BufferedInputStream
 Let's see the simple example to read data of file
using BufferedInputStream.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class SimpleRead{
 public static void main(String args[]){
 try{
 FileInputStream fin=new FileInputStream("f1.txt");
 BufferedInputStream bin=new BufferedInputStream(fin);
 int i;
 while((i=bin.read())!=-1){
 System.out.println((char)i);
 }
 bin.close();
 fin.close();
 }catch(Exception e){system.out.println(e);}
 }
 }
 Output:
 Sachin is my favourite player
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA FILEWRITER AND FILEREADER (FILE
HANDLING IN JAVA)
 Java FileWriter and FileReader classes are used to
write and read data from text files. These are
character-oriented classes, used for file handling in
java.
 Java has suggested not to use the FileInputStream
and FileOutputStream classes if you have to read
and write the textual information.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Java FileWriter class
 Java FileWriter class is used to write character-
oriented data to the file.
BYLECTURERSURAJPANDEYCCT
COLLEGE
CONSTRUCTORS OF FILEWRITER CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
METHODS OF FILEWRITER CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Java FileWriter Example
 In this example, we are writing the data in the file
abc.txt.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class Simple{
 public static void main(String args[]){
 try{
 FileWriter fw=new FileWriter("abc.txt");
 fw.write("my name is sachin");
 fw.close();
 }catch(Exception e){System.out.println(e);}
 System.out.println("success");
 }
 }
 Output:
 success...
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA FILEREADER CLASS
 Java FileReader class is used to read data from the
file. It returns data in byte format like
FileInputStream class.
BYLECTURERSURAJPANDEYCCT
COLLEGE
CONSTRUCTORS OF FILEWRITER CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
METHODS OF FILEREADER CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Java FileReader Example
 In this example, we are reading the data from the
file abc.txt file.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class Simple{
 public static void main(String args[])throws Exception
{
 FileReader fr=new FileReader("abc.txt");
 int i;
 while((i=fr.read())!=-1)
 System.out.println((char)i);
 fr.close();
 }
 }
 Output:
 my name is sachin
BYLECTURERSURAJPANDEYCCT
COLLEGE
CHARARRAYWRITER CLASS:
 The CharArrayWriter class can be used to write
data to multiple files. This class implements the
Appendable interface. Its buffer automatically grows
when data is written in this stream. Calling the
close() method on this object has no effect.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Example of CharArrayWriter class:
 In this example, we are writing a common data to 4
files a.txt, b.txt, c.txt and d.txt.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class Simple{
 public static void main(String args[])throws Exception{
 CharArrayWriter out=new CharArrayWriter();
 out.write("my name is");
 FileWriter f1=new FileWriter("a.txt");
 FileWriter f2=new FileWriter("b.txt");
 FileWriter f3=new FileWriter("c.txt");
 FileWriter f4=new FileWriter("d.txt");
 out.writeTo(f1);
 out.writeTo(f2);
 out.writeTo(f3);
 out.writeTo(f4);
 f1.close();
 f2.close();
 f3.close();
 f4.close();
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
READING DATA FROM KEYBOARD
 There are many ways to read data from the
keyboard. For example:
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 InputStreamReader class
 InputStreamReader class can be used to read data
from keyboard.It performs two tasks:
 connects to input stream of keyboard
 converts the byte-oriented stream into character-
oriented stream
 BufferedReader class
 BufferedReader class can be used to read data line
by line by readLine() method.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Example of reading data from keyboard by
InputStreamReader and BufferdReader class
 In this example, we are connecting the
BufferedReader stream with the
InputStreamReader stream for reading the line by
line data from the keyboard.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class G5{
 public static void main(String args[])throws Exception{

 InputStreamReader r=new InputStreamReader(System.in);
 BufferedReader br=new BufferedReader(r);

 System.out.println("Enter your name");
 String name=br.readLine();
 System.out.println("Welcome "+name);
 }
 }
 Output:Enter your name
 Amit
 Welcome Amit
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Another Example of reading data from keyboard by
InputStreamReader and BufferdReader class until
the user writes stop
 In this example, we are reading and printing the
data until the user prints stop.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class G5{
 public static void main(String args[])throws Exception{
 InputStreamReader r=new InputStreamReader(System.in);
 BufferedReader br=new BufferedReader(r);
 String name="";
 while(!name.equals("stop")){
 System.out.println("Enter data: ");
 name=br.readLine();
 System.out.println("data is: "+name);
 }
 br.close();
 r.close();
 }
 }
 Output:Enter data: Amit
 data is: Amit
 Enter data: 10
 data is: 10
 Enter data: stop
 data is: stop
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Java Console class
 The Java Console class is be used to get input from
console. It provides methods to read text and
password.
 If you read password using Console class, it will not
be displayed to the user.
 The java.io.Console class is attached with system
console internally. The Console class is introduced
since 1.5.
 Let's see a simple example to read text from
console.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 String text=System.console().readLine();
 System.out.println("Text is: "+text);
BYLECTURERSURAJPANDEYCCT
COLLEGE
METHODS OF CONSOLE CLASS
BYLECTURERSURAJPANDEYCCT
COLLEGE
HOW TO GET THE OBJECT OF CONSOLE
 System class provides a static method console()
that returns the unique instance of Console class.
 public static Console console(){}
 Let's see the code to get the instance of Console
class.
 Console c=System.console();
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA CONSOLE EXAMPLE
 import java.io.*;
 class ReadStringTest{
 public static void main(String args[]){
 Console c=System.console();
 System.out.println("Enter your name: ");
 String n=c.readLine();
 System.out.println("Welcome "+n);
 }
 }
 Output:
 Enter your name: james gosling
 Welcome james gosling
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA CONSOLE EXAMPLE TO READ PASSWORD
 import java.io.*;
 class ReadPasswordTest{
 public static void main(String args[]){
 Console c=System.console();
 System.out.println("Enter password: ");
 char[] ch=c.readPassword();
 String pass=String.valueOf(ch);//converting char array in
to string
 System.out.println("Password is: "+pass);
 }
 }
 Output:
 Enter password:
 Password is: sonoo
BYLECTURERSURAJPANDEYCCT
COLLEGE
JAVA SCANNER CLASS
 There are various ways to read input from the
keyboard, the java.util.Scanner class is one of
them.
 The Java Scanner class breaks the input into
tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and
parse various primitive values.
 Java Scanner class is widely used to parse text for
string and primitive types using regular expression.
 Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Commonly used methods of Scanner class
 There is a list of commonly used Scanner class
methods:
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
 The Java Scanner class breaks the input into
tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and
parse various primitive values.
 Java Scanner class is widely used to parse text for
string and primitive types using regular expression.
 Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Commonly used methods of Scanner class
 There is a list of commonly used Scanner class
methods:
 Java Scanner Example to get input from console
 Let's see the simple example of the Java Scanner
class which reads the int, string and double value
as an input:
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.util.Scanner;
 class ScannerTest{
 public static void main(String args[]){
 Scanner sc=new Scanner(System.in);

 System.out.println("Enter your rollno");
 int rollno=sc.nextInt();
 System.out.println("Enter your name");
 String name=sc.next();
 System.out.println("Enter your fee");
 double fee=sc.nextDouble();
 System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee
);
 sc.close();
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Enter your rollno 111 Enter your name
Ratan Enter 450000 Rollno:111
name:Ratan fee:450000
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Java Scanner Example with delimiter
 Let's see the example of Scanner class with
delimiter. The s represents whitespace.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.util.*;
 public class ScannerTest2{
 public static void main(String args[]){
 String input = "10 tea 20 coffee 30 tea buiscuits";
 Scanner s = new Scanner(input).useDelimiter("s");
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 s.close();
 }}
 Output:
 10tea20coffee
BYLECTURERSURAJPANDEYCCT
COLLEGE
 java.io.PrintStream class:
 The PrintStream class provides methods to write
data to another stream. The PrintStream class
automatically flushes the data so there is no need
to call flush() method. Moreover, its methods don't
throw IOException.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 There are many methods in PrintStream class. Let's see commonly used
methods of PrintStream class:
 public void print(boolean b): it prints the specified boolean value.
 public void print(char c): it prints the specified char value.
 public void print(char[] c): it prints the specified character array values.
 public void print(int i): it prints the specified int value.
 public void print(long l): it prints the specified long value.
 public void print(float f): it prints the specified float value.
 public void print(double d): it prints the specified double value.
 public void print(String s): it prints the specified string value.
 public void print(Object obj): it prints the specified object value.
 public void println(boolean b): it prints the specified boolean value and
terminates the line.
 public void println(char c): it prints the specified char value and
terminates the line.
 public void println(char[] c): it prints the specified character array
values and terminates the line.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 public void println(int i): it prints the specified int value and terminates the line.
 public void println(long l): it prints the specified long value and terminates the
line.
 public void println(float f): it prints the specified float value and terminates the
line.
 public void println(double d): it prints the specified double value and terminates
the line.
 public void println(String s): it prints the specified string value and terminates the
line./li>
 public void println(Object obj): it prints the specified object value and terminates
the line.
 public void println(): it terminates the line only.
 public void printf(Object format, Object... args): it writes the formatted string to
the current stream.
 public void printf(Locale l, Object format, Object... args): it writes the formatted
string to the current stream.
 public void format(Object format, Object... args): it writes the formatted string to
the current stream using specified format.
 public void format(Locale l, Object format, Object... args): it writes the
formatted string to the current stream using specified format.
BYLECTURERSURAJPANDEYCCT
COLLEGE
EXAMPLE OF JAVA.IO.PRINTSTREAM CLASS:
 In this example, we are simply printing integer and
string values.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 class PrintStreamTest{
 public static void main(String args[])throws Exception{
 FileOutputStream fout=new FileOutputStream("mfile.txt");
 PrintStream pout=new PrintStream(fout);
 pout.println(1900);
 pout.println("Hello Java");
 pout.println("Welcome to Java");
 pout.close();
 fout.close();

 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Example of printf() method of java.io.PrintStream
class:
 Let's see the simple example of printing integer
value by format specifier.
BYLECTURERSURAJPANDEYCCT
COLLEGE
 class PrintStreamTest{
 public static void main(String args[]){
 int a=10;
 System.out.printf("%d",a);//Note, out is the object
of PrintStream class

 }
 }
 Output:10
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Compressing and Uncompressing File
 The DeflaterOutputStream and InflaterInputStream
classes provide mechanism to compress and
uncompress the data in the deflate compression
format.
 DeflaterOutputStream class:
 The DeflaterOutputStream class is used to compress
the data in the deflate compression format. It provides
facility to the other compression filters, such as
GZIPOutputStream.
 Example of Compressing file using
DeflaterOutputStream class
 In this example, we are reading data of a file and
compressing it into another file using
DeflaterOutputStream class. You can compress any file,
here we are compressing the Deflater.java file
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 import java.util.zip.*;
 class Compress{
 public static void main(String args[]){
 try{
 FileInputStream fin=new FileInputStream("Deflater.java");
 FileOutputStream fout=new FileOutputStream("def.txt");
 DeflaterOutputStream out=new DeflaterOutputStream(fout);
 int i;
 while((i=fin.read())!=-1){
 out.write((byte)i);
 out.flush();
 }
 fin.close();
 out.close();
 }catch(Exception e){System.out.println(e);}
 System.out.println("rest of the code");
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 InflaterInputStream class:
 The InflaterInputStream class is used to
uncompress the file in the deflate compression
format. It provides facility to the other
uncompression filters, such as GZIPInputStream
class.
 Example of uncompressing file using
InflaterInputStream class
 In this example, we are decompressing the
compressed file def.txt into D.java .
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
 import java.util.zip.*;
 class UnCompress{
 public static void main(String args[]){
 try{
 FileInputStream fin=new FileInputStream("def.txt");
 InflaterInputStream in=new InflaterInputStream(fin);
 FileOutputStream fout=new FileOutputStream("D.java");
 int i;
 while((i=in.read())!=-1){
 fout.write((byte)i);
 fout.flush();
 }
 fin.close();
 fout.close();
 in.close();
 }catch(Exception e){System.out.println(e);}
 System.out.println("rest of the code");
 }
 }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Java provides strong but flexible support for I/O
related to Files and networks but this tutorial covers
very basic functionality related to streams and I/O.
We would see most commonly used example one
by one:
 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:
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close(); }
if (out != null)
{
out.close();
} } } }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Character Streams
 Java Byte streams are used to perform input and output
of 8-bit bytes, where as 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.. Though internally
FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here major difference is that
FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
 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:
BYLECTURERSURAJPANDEYCCT
COLLEGE
 import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
} } } }
BYLECTURERSURAJPANDEYCCT
COLLEGE
 Reading and Writing Files:
 As described earlier, A stream can be defined as a
sequence of data. TheInputStream is used to read
data from a source and the OutputStream is used
for writing data to a destination.
 Here is a hierarchy of classes to deal with Input and
Output streams.
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
 The two important streams
are FileInputStream and FileOutputStream,
which would be discussed in this tutorial:
 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");
BYLECTURERSURAJPANDEYCCT
COLLEGE
 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);Once you
have InputStream object in hand, then there is a list
of helper methods which can be used to read to
stream or to do other operations on the stream.
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE
BYLECTURERSURAJPANDEYCCT
COLLEGE

More Related Content

PDF
What is java input and output stream?
PPT
Chapter 12 - File Input and Output
PDF
Java I/o streams
PDF
Java IO
PPTX
Input output files in java
What is java input and output stream?
Chapter 12 - File Input and Output
Java I/o streams
Java IO
Input output files in java

What's hot (20)

PPT
Java stream
PPTX
Java I/O
PPTX
Multithreading in java
PPTX
Understanding java streams
PDF
Ppl for students unit 4 and 5
PDF
Java programming basics
PPTX
Multithreading in java
PPT
Taking User Input in Java
PPT
Java Multithreading and Concurrency
PDF
Java Course 8: I/O, Files and Streams
PPT
File Input & Output
PPTX
PPTX
L21 io streams
PPTX
MULTI THREADING IN JAVA
PDF
Java Concurrency by Example
PPT
Java Streams
PPTX
Chapter 10.3
PDF
Multithreading in Java
PPTX
Basic of java
PDF
Java Threads
Java stream
Java I/O
Multithreading in java
Understanding java streams
Ppl for students unit 4 and 5
Java programming basics
Multithreading in java
Taking User Input in Java
Java Multithreading and Concurrency
Java Course 8: I/O, Files and Streams
File Input & Output
L21 io streams
MULTI THREADING IN JAVA
Java Concurrency by Example
Java Streams
Chapter 10.3
Multithreading in Java
Basic of java
Java Threads
Ad

Similar to Basic of Javaio (20)

PPTX
Java Input Output (java.io.*)
PDF
Java Day-6
PDF
What is java input and output stream?
PPTX
DOC-20240802-WA00cggyggrrrggyyyy06..pptx
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
PPTX
Input & output
PPTX
2.1 (1) (1).pptx new new new new newner o
DOC
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
PPTX
Java Tutorial Lab 6
PDF
Advanced programming ch2
PDF
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
PPTX
IOStream.pptx
PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
PDF
CSE3146-ADV JAVA M2.pdf
PDF
26 io -ii file handling
PPTX
Input/Output Exploring java.io
PPTX
Javaiostream
Java Input Output (java.io.*)
Java Day-6
What is java input and output stream?
DOC-20240802-WA00cggyggrrrggyyyy06..pptx
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Input & output
2.1 (1) (1).pptx new new new new newner o
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Java Tutorial Lab 6
Advanced programming ch2
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOStream.pptx
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
Itp 120 Chapt 19 2009 Binary Input & Output
CSE3146-ADV JAVA M2.pdf
26 io -ii file handling
Input/Output Exploring java.io
Javaiostream
Ad

More from suraj pandey (20)

PPT
Systemcare in computer
PPT
vb.net Constructor and destructor
PPTX
Overloading and overriding in vb.net
PPT
Basic in Computernetwork
PPT
Computer hardware
PPT
Dos commands new
PPT
History of computer
PPT
Dos commands
PPT
Basic of Internet&email
PPT
Basic fundamental Computer input/output Accessories
PPT
Introduction of exception in vb.net
PPT
Transmission mediums in computer networks
PPTX
Introduction to vb.net
PPT
Introduction to computer
PPT
Computer Fundamental Network topologies
PPTX
Basic of Computer software
PPT
Basic using of Swing in Java
PPT
Basic Networking in Java
PPT
Basic Java Database Connectivity(JDBC)
PPT
Graphical User Interface in JAVA
Systemcare in computer
vb.net Constructor and destructor
Overloading and overriding in vb.net
Basic in Computernetwork
Computer hardware
Dos commands new
History of computer
Dos commands
Basic of Internet&email
Basic fundamental Computer input/output Accessories
Introduction of exception in vb.net
Transmission mediums in computer networks
Introduction to vb.net
Introduction to computer
Computer Fundamental Network topologies
Basic of Computer software
Basic using of Swing in Java
Basic Networking in Java
Basic Java Database Connectivity(JDBC)
Graphical User Interface in JAVA

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
master seminar digital applications in india
PDF
Pre independence Education in Inndia.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Institutional Correction lecture only . . .
PDF
TR - Agricultural Crops Production NC III.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
human mycosis Human fungal infections are called human mycosis..pptx
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Final Presentation General Medicine 03-08-2024.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Basic Mud Logging Guide for educational purpose
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
master seminar digital applications in india
Pre independence Education in Inndia.pdf
Computing-Curriculum for Schools in Ghana
Institutional Correction lecture only . . .
TR - Agricultural Crops Production NC III.pdf

Basic of Javaio

  • 2.  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.  We can perform file handling in java by java IO API. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 3. 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 BYLECTURERSURAJPANDEYCCT COLLEGE
  • 4.  Let's see the code to print output and error message to the console. 1. System.out.println("simple message"); 2. System.err.println("error message"); BYLECTURERSURAJPANDEYCCT COLLEGE
  • 5.  Let's see the code to get input from console. 1. int i=System.in.read();//returns ASCII code of 1st c haracter 2. System.out.println((char)i);//will print the character BYLECTURERSURAJPANDEYCCT COLLEGE
  • 6.  The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.  Stream  A stream can be defined as a sequence of data. there are two kinds of Streams  InPutStream: The InputStream is used to read data from a source.  OutPutStream: the OutputStream is used for writing data to a destination. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 7. LET'S UNDERSTAND WORKING OF JAVA OUTPUTSTREAM AND INPUTSTREAM BY THE FIGURE GIVEN BELOW. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 8. OUTPUTSTREAM CLASS  OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 11.  InputStream class  InputStream class is an abstract class.It is the superclass of all classes representing an input stream of bytes. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 14. FILEINPUTSTREAM AND FILEOUTPUTSTREAM (FILE HANDLING)  In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 15. JAVA FILEOUTPUTSTREAM CLASS  Java FileOutputStream is an output stream for writing data to a file.  If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you can write byte- oriented as well as character-oriented data. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 16. EXAMPLE OF JAVA FILEOUTPUTSTREAM CLASS  import java.io.*;  class Test{  public static void main(String args[]){  try{  FileOutputstream fout=new FileOutputStream("abc.txt");  String s="Sachin Tendulkar is my favourite player";  byte b[]=s.getBytes();//converting string into byte array  fout.write(b);  fout.close();  System.out.println("success...");  }catch(Exception e){system.out.println(e);}  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 18. JAVA FILEINPUTSTREAM CLASS  Java FileInputStream class obtains input bytes from a file.It is used for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.  It should be used to read byte-oriented data for example to read image, audio, video etc. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 19. EXAMPLE OF FILEINPUTSTREAM CLASS  import java.io.*;  class SimpleRead{  public static void main(String args[]){  try{  FileInputStream fin=new FileInputStream("abc.txt");  int i=0;  while((i=fin.read())!=-1){  System.out.println((char)i);  }  fin.close();  }catch(Exception e){system.out.println(e);}  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 20.  Output:Sachin is my favourite player. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 22. 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. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 23.  import java.io.*;  class C{  public static void main(String args[])throws Exception{  FileInputStream fin=new FileInputStream("C.java");  FileOutputStream fout=new FileOutputStream("M.java");  int i=0;  while((i=fin.read())!=-1){  fout.write((byte)i);  }  fin.close();  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 24. JAVA BYTEARRAYOUTPUTSTREAM CLASS  Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the data is written into a byte array that can be written to multiple stream.  The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.  The buffer of ByteArrayOutputStream automatically grows according to data.  Closing the ByteArrayOutputStream has no effect. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 26. METHODS OF BYTEARRAYOUTPUTSTREAM CLASS BYLECTURERSURAJPANDEYCCT COLLEGE
  • 27. JAVA BYTEARRAYOUTPUTSTREAM EXAMPLE  Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 28.  import java.io.*;  class S{  public static void main(String args[])throws Exception{  FileOutputStream fout1=new FileOutputStream("f1.txt");  FileOutputStream fout2=new FileOutputStream("f2.txt");  ByteArrayOutputStream bout=new ByteArrayOutputStream();  bout.write(139);  bout.writeTo(fout1);  bout.writeTo(fout2);  bout.flush();  bout.close();//has no effect  System.out.println("success...");  }  }  success... BYLECTURERSURAJPANDEYCCT COLLEGE
  • 30. JAVA SEQUENCEINPUTSTREAM CLASS  Java SequenceInputStream class is used to read data from multiple streams. It reads data of streams one by one. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 32.  Constructors of SequenceInputStream class:  Simple example of SequenceInputStream class  In this example, we are printing the data of two files f1.txt and f2.txt. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 33.  import java.io.*;  class Simple{  public static void main(String args[])throws Exception{  FileinputStream fin1=new FileinputStream("f1.txt");  FileinputStream fin2=new FileinputStream("f2.txt");  SequenceinputStream sis=new SequenceinputStream(fin1,fin2 );  int i;  while((i=sis.read())!=-1){  System.out.println((char)i);  }  sis.close();  fin1.close();  fin2.close();  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 34. EXAMPLE OF SEQUENCEINPUTSTREAM THAT READS THE DATA FROM TWO FILES  In this example, we are writing the data of two files f1.txt and f2.txt into another file named f3.txt. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 35.  //reading data of 2 files and writing it into one file  import java.io.*;  class Simple{  public static void main(String args[])throws Exception{  FileinputStream fin1=new FileinputStream("f1.txt");  FileinputStream fin2=new FileinputStream("f2.txt");  FileOutputStream fout=new FileOutputStream("f3.txt");  SequenceinputStream sis=new SequenceinputStream(fin1,fin2);  int i;  while((i.sisread())!=-1)  {  fout.write(i);  }  sis.close();  fout.close();  fin.close();  fin.close();  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 36. EXAMPLE OF SEQUENCEINPUTSTREAM CLASS THAT READS THE DATA FROM MULTIPLE FILES USING ENUMERATION  If we need to read the data from more than two files, we need to have these information in the Enumeration object. Enumeration object can be get by calling elements method of the Vector class. Let's see the simple example where we are reading the data from the 4 files. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 37.  import java.io.*;  import java.util.*;  class B{  public static void main(String args[])throws IOException{  //creating the FileInputStream objects for all the files  FileInputStream fin=new FileInputStream("A.java");  FileInputStream fin2=new FileInputStream("abc2.txt");  FileInputStream fin3=new FileInputStream("abc.txt");  FileInputStream fin4=new FileInputStream("B.java");  //creating Vector object to all the stream  Vector v=new Vector();  v.add(fin);  v.add(fin2);  v.add(fin3);  v.add(fin4);  //creating enumeration object by calling the elements method  Enumeration e=v.elements();  //passing the enumeration object in the constructor  SequenceInputStream bin=new SequenceInputStream(e);  int i=0;  while((i=bin.read())!=-1){  System.out.print((char)i);  }  bin.close();  fin.close();  fin2.close();  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 38. JAVA BUFFEREDOUTPUTSTREAM AND BUFFEREDINPUTSTREAM  Java BufferedOutputStream class  Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 39.  Example of BufferedOutputStream class:  In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 40.  import java.io.*;  class Test{  public static void main(String args[])throws Exception{  FileOutputStream fout=new FileOutputStream("f1.txt");  BufferedOutputStream bout=new BufferedOutputStream(fout);  String s="Sachin is my favourite player";  byte b[]=s.getBytes();  bout.write(b);  bout.flush();  bout.close();  fout.close();  System.out.println("success");  }  }  Output:  success... BYLECTURERSURAJPANDEYCCT COLLEGE
  • 41. JAVA BUFFEREDINPUTSTREAM CLASS  Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.  Example of Java BufferedInputStream  Let's see the simple example to read data of file using BufferedInputStream. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 42.  import java.io.*;  class SimpleRead{  public static void main(String args[]){  try{  FileInputStream fin=new FileInputStream("f1.txt");  BufferedInputStream bin=new BufferedInputStream(fin);  int i;  while((i=bin.read())!=-1){  System.out.println((char)i);  }  bin.close();  fin.close();  }catch(Exception e){system.out.println(e);}  }  }  Output:  Sachin is my favourite player BYLECTURERSURAJPANDEYCCT COLLEGE
  • 43. JAVA FILEWRITER AND FILEREADER (FILE HANDLING IN JAVA)  Java FileWriter and FileReader classes are used to write and read data from text files. These are character-oriented classes, used for file handling in java.  Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and write the textual information. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 44.  Java FileWriter class  Java FileWriter class is used to write character- oriented data to the file. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 45. CONSTRUCTORS OF FILEWRITER CLASS BYLECTURERSURAJPANDEYCCT COLLEGE
  • 46. METHODS OF FILEWRITER CLASS BYLECTURERSURAJPANDEYCCT COLLEGE
  • 47.  Java FileWriter Example  In this example, we are writing the data in the file abc.txt. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 48.  import java.io.*;  class Simple{  public static void main(String args[]){  try{  FileWriter fw=new FileWriter("abc.txt");  fw.write("my name is sachin");  fw.close();  }catch(Exception e){System.out.println(e);}  System.out.println("success");  }  }  Output:  success... BYLECTURERSURAJPANDEYCCT COLLEGE
  • 49. JAVA FILEREADER CLASS  Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 50. CONSTRUCTORS OF FILEWRITER CLASS BYLECTURERSURAJPANDEYCCT COLLEGE
  • 51. METHODS OF FILEREADER CLASS BYLECTURERSURAJPANDEYCCT COLLEGE
  • 52.  Java FileReader Example  In this example, we are reading the data from the file abc.txt file. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 53.  import java.io.*;  class Simple{  public static void main(String args[])throws Exception {  FileReader fr=new FileReader("abc.txt");  int i;  while((i=fr.read())!=-1)  System.out.println((char)i);  fr.close();  }  }  Output:  my name is sachin BYLECTURERSURAJPANDEYCCT COLLEGE
  • 54. CHARARRAYWRITER CLASS:  The CharArrayWriter class can be used to write data to multiple files. This class implements the Appendable interface. Its buffer automatically grows when data is written in this stream. Calling the close() method on this object has no effect. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 55.  Example of CharArrayWriter class:  In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 56.  import java.io.*;  class Simple{  public static void main(String args[])throws Exception{  CharArrayWriter out=new CharArrayWriter();  out.write("my name is");  FileWriter f1=new FileWriter("a.txt");  FileWriter f2=new FileWriter("b.txt");  FileWriter f3=new FileWriter("c.txt");  FileWriter f4=new FileWriter("d.txt");  out.writeTo(f1);  out.writeTo(f2);  out.writeTo(f3);  out.writeTo(f4);  f1.close();  f2.close();  f3.close();  f4.close();  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 57. READING DATA FROM KEYBOARD  There are many ways to read data from the keyboard. For example: 1. InputStreamReader 2. Console 3. Scanner 4. DataInputStream etc. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 58.  InputStreamReader class  InputStreamReader class can be used to read data from keyboard.It performs two tasks:  connects to input stream of keyboard  converts the byte-oriented stream into character- oriented stream  BufferedReader class  BufferedReader class can be used to read data line by line by readLine() method. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 59.  Example of reading data from keyboard by InputStreamReader and BufferdReader class  In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 60.  import java.io.*;  class G5{  public static void main(String args[])throws Exception{   InputStreamReader r=new InputStreamReader(System.in);  BufferedReader br=new BufferedReader(r);   System.out.println("Enter your name");  String name=br.readLine();  System.out.println("Welcome "+name);  }  }  Output:Enter your name  Amit  Welcome Amit BYLECTURERSURAJPANDEYCCT COLLEGE
  • 62.  Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop  In this example, we are reading and printing the data until the user prints stop. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 63.  import java.io.*;  class G5{  public static void main(String args[])throws Exception{  InputStreamReader r=new InputStreamReader(System.in);  BufferedReader br=new BufferedReader(r);  String name="";  while(!name.equals("stop")){  System.out.println("Enter data: ");  name=br.readLine();  System.out.println("data is: "+name);  }  br.close();  r.close();  }  }  Output:Enter data: Amit  data is: Amit  Enter data: 10  data is: 10  Enter data: stop  data is: stop BYLECTURERSURAJPANDEYCCT COLLEGE
  • 64.  Java Console class  The Java Console class is be used to get input from console. It provides methods to read text and password.  If you read password using Console class, it will not be displayed to the user.  The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.  Let's see a simple example to read text from console. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 65.  String text=System.console().readLine();  System.out.println("Text is: "+text); BYLECTURERSURAJPANDEYCCT COLLEGE
  • 66. METHODS OF CONSOLE CLASS BYLECTURERSURAJPANDEYCCT COLLEGE
  • 67. HOW TO GET THE OBJECT OF CONSOLE  System class provides a static method console() that returns the unique instance of Console class.  public static Console console(){}  Let's see the code to get the instance of Console class.  Console c=System.console(); BYLECTURERSURAJPANDEYCCT COLLEGE
  • 68. JAVA CONSOLE EXAMPLE  import java.io.*;  class ReadStringTest{  public static void main(String args[]){  Console c=System.console();  System.out.println("Enter your name: ");  String n=c.readLine();  System.out.println("Welcome "+n);  }  }  Output:  Enter your name: james gosling  Welcome james gosling BYLECTURERSURAJPANDEYCCT COLLEGE
  • 69. JAVA CONSOLE EXAMPLE TO READ PASSWORD  import java.io.*;  class ReadPasswordTest{  public static void main(String args[]){  Console c=System.console();  System.out.println("Enter password: ");  char[] ch=c.readPassword();  String pass=String.valueOf(ch);//converting char array in to string  System.out.println("Password is: "+pass);  }  }  Output:  Enter password:  Password is: sonoo BYLECTURERSURAJPANDEYCCT COLLEGE
  • 70. JAVA SCANNER CLASS  There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.  The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values.  Java Scanner class is widely used to parse text for string and primitive types using regular expression.  Java Scanner class extends Object class and implements Iterator and Closeable interfaces. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 71.  Commonly used methods of Scanner class  There is a list of commonly used Scanner class methods: BYLECTURERSURAJPANDEYCCT COLLEGE
  • 74.  The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values.  Java Scanner class is widely used to parse text for string and primitive types using regular expression.  Java Scanner class extends Object class and implements Iterator and Closeable interfaces. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 75.  Commonly used methods of Scanner class  There is a list of commonly used Scanner class methods:  Java Scanner Example to get input from console  Let's see the simple example of the Java Scanner class which reads the int, string and double value as an input: BYLECTURERSURAJPANDEYCCT COLLEGE
  • 76.  import java.util.Scanner;  class ScannerTest{  public static void main(String args[]){  Scanner sc=new Scanner(System.in);   System.out.println("Enter your rollno");  int rollno=sc.nextInt();  System.out.println("Enter your name");  String name=sc.next();  System.out.println("Enter your fee");  double fee=sc.nextDouble();  System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee );  sc.close();  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 77.  Enter your rollno 111 Enter your name Ratan Enter 450000 Rollno:111 name:Ratan fee:450000 BYLECTURERSURAJPANDEYCCT COLLEGE
  • 78.  Java Scanner Example with delimiter  Let's see the example of Scanner class with delimiter. The s represents whitespace. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 79.  import java.util.*;  public class ScannerTest2{  public static void main(String args[]){  String input = "10 tea 20 coffee 30 tea buiscuits";  Scanner s = new Scanner(input).useDelimiter("s");  System.out.println(s.nextInt());  System.out.println(s.next());  System.out.println(s.nextInt());  System.out.println(s.next());  s.close();  }}  Output:  10tea20coffee BYLECTURERSURAJPANDEYCCT COLLEGE
  • 80.  java.io.PrintStream class:  The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't throw IOException. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 81.  There are many methods in PrintStream class. Let's see commonly used methods of PrintStream class:  public void print(boolean b): it prints the specified boolean value.  public void print(char c): it prints the specified char value.  public void print(char[] c): it prints the specified character array values.  public void print(int i): it prints the specified int value.  public void print(long l): it prints the specified long value.  public void print(float f): it prints the specified float value.  public void print(double d): it prints the specified double value.  public void print(String s): it prints the specified string value.  public void print(Object obj): it prints the specified object value.  public void println(boolean b): it prints the specified boolean value and terminates the line.  public void println(char c): it prints the specified char value and terminates the line.  public void println(char[] c): it prints the specified character array values and terminates the line. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 82.  public void println(int i): it prints the specified int value and terminates the line.  public void println(long l): it prints the specified long value and terminates the line.  public void println(float f): it prints the specified float value and terminates the line.  public void println(double d): it prints the specified double value and terminates the line.  public void println(String s): it prints the specified string value and terminates the line./li>  public void println(Object obj): it prints the specified object value and terminates the line.  public void println(): it terminates the line only.  public void printf(Object format, Object... args): it writes the formatted string to the current stream.  public void printf(Locale l, Object format, Object... args): it writes the formatted string to the current stream.  public void format(Object format, Object... args): it writes the formatted string to the current stream using specified format.  public void format(Locale l, Object format, Object... args): it writes the formatted string to the current stream using specified format. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 83. EXAMPLE OF JAVA.IO.PRINTSTREAM CLASS:  In this example, we are simply printing integer and string values. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 84.  import java.io.*;  class PrintStreamTest{  public static void main(String args[])throws Exception{  FileOutputStream fout=new FileOutputStream("mfile.txt");  PrintStream pout=new PrintStream(fout);  pout.println(1900);  pout.println("Hello Java");  pout.println("Welcome to Java");  pout.close();  fout.close();   }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 85.  Example of printf() method of java.io.PrintStream class:  Let's see the simple example of printing integer value by format specifier. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 86.  class PrintStreamTest{  public static void main(String args[]){  int a=10;  System.out.printf("%d",a);//Note, out is the object of PrintStream class   }  }  Output:10 BYLECTURERSURAJPANDEYCCT COLLEGE
  • 87.  Compressing and Uncompressing File  The DeflaterOutputStream and InflaterInputStream classes provide mechanism to compress and uncompress the data in the deflate compression format.  DeflaterOutputStream class:  The DeflaterOutputStream class is used to compress the data in the deflate compression format. It provides facility to the other compression filters, such as GZIPOutputStream.  Example of Compressing file using DeflaterOutputStream class  In this example, we are reading data of a file and compressing it into another file using DeflaterOutputStream class. You can compress any file, here we are compressing the Deflater.java file BYLECTURERSURAJPANDEYCCT COLLEGE
  • 88.  import java.io.*;  import java.util.zip.*;  class Compress{  public static void main(String args[]){  try{  FileInputStream fin=new FileInputStream("Deflater.java");  FileOutputStream fout=new FileOutputStream("def.txt");  DeflaterOutputStream out=new DeflaterOutputStream(fout);  int i;  while((i=fin.read())!=-1){  out.write((byte)i);  out.flush();  }  fin.close();  out.close();  }catch(Exception e){System.out.println(e);}  System.out.println("rest of the code");  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 89.  InflaterInputStream class:  The InflaterInputStream class is used to uncompress the file in the deflate compression format. It provides facility to the other uncompression filters, such as GZIPInputStream class.  Example of uncompressing file using InflaterInputStream class  In this example, we are decompressing the compressed file def.txt into D.java . BYLECTURERSURAJPANDEYCCT COLLEGE
  • 90.  import java.io.*;  import java.util.zip.*;  class UnCompress{  public static void main(String args[]){  try{  FileInputStream fin=new FileInputStream("def.txt");  InflaterInputStream in=new InflaterInputStream(fin);  FileOutputStream fout=new FileOutputStream("D.java");  int i;  while((i=in.read())!=-1){  fout.write((byte)i);  fout.flush();  }  fin.close();  fout.close();  in.close();  }catch(Exception e){System.out.println(e);}  System.out.println("rest of the code");  }  } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 91.  Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one:  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: BYLECTURERSURAJPANDEYCCT COLLEGE
  • 92.  import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 93.  Character Streams  Java Byte streams are used to perform input and output of 8-bit bytes, where as 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.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.  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: BYLECTURERSURAJPANDEYCCT COLLEGE
  • 94.  import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } BYLECTURERSURAJPANDEYCCT COLLEGE
  • 95.  Reading and Writing Files:  As described earlier, A stream can be defined as a sequence of data. TheInputStream is used to read data from a source and the OutputStream is used for writing data to a destination.  Here is a hierarchy of classes to deal with Input and Output streams. BYLECTURERSURAJPANDEYCCT COLLEGE
  • 97.  The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial:  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"); BYLECTURERSURAJPANDEYCCT COLLEGE
  • 98.  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);Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream. BYLECTURERSURAJPANDEYCCT COLLEGE