You are on page 1of 39

I/O STREAMS

OUTLINE:

 Class Hierarchy

 2. Read/Write Console

Unit-I
 3. Reading and Writing in Files

- Byte Stream

-Character Stream
CLASS HIERARCHY
Stream

ByteStreamClasses

Unit-I
CharStreamClasses

OutputStream InputStream

Reader writer
CLASS HIERARCHY:

Reader Writer

Buffere Input Buffere


d Stream Print d
Reader Reader Writer Writer

Unit-I
Filter File
Reader Reader Output
File
Stream
Writer
Writer
Input
Stream
Output
Stream
Filter Object FileInpu
Input Input t
Stream Stream Stream
Object File
Filter
Output Output
Output
Stream Stream
Stream
Buffere
Data
d
Input
Input
Stream
Stream Data Buffered
Output Output
Stream Stream
INPUTSTREAM

Unit-I
OUTPUTSTREAM

Unit-I
READING AND WRITING FILES
Java.io.File class
- used for reading and writing a file

Method in file class:


 f.exists()

 f.canRead()

Unit-I
 f.canWrite()

 f.getName()

 f.getParent()

 f.getPath()

 f.isHidden()

 f.length()

 f.lastModified()

 f.isFile()

 f.list()

 f.isDirectory() etc…
import java.io.*;
class Filedemo{
public static void main(String args[]){
File f=new File(args[0]);
System.out.println("fileExists:" +f.exists());
System.out.println("file can be read:" +f.canRead());
System.out.println("file can be written:"+f.canWrite());
System.out.println("file can be executed:"+f.canExecute());
System.out.println("file name:"+f.getName());
System.out.println("parent of file:" +f.getParent());

Unit-I
System.out.println("path of file:"+f.getPath());
System.out.println("Hiddenfile:"+f.isHidden());
System.out.println("lengthoffile:"+f.length());
System.out.println("lastmodifiedtime:"+f.lastModified());
System.out.println("it is a file:"+ f.isFile());
if(f.isDirectory()) {
System.out.println(f.getPath()+ "is a Directory");
String l[]=f.list();
System.out.println("Directory List" +f.getPath() +"is");
for(String a:l) {
File f1=new File(f.getPath()+ "/"+a);
if(f1.isDirectory()) {
System.out.println( a+" Directory");
f1=null; }
else {
System.out.println( a+"isFile");
f1=null;
}}}} }
OUTPUT:

Unit-I
READING AND WRITING FILES USING BYTE STREAM

 FileInputStream(String fileName) throws


FileNotFoundException
 FileOutputStream(String fileName) throws
FileNotFoundException
Example: (Writing into file)
class Test{

Unit-I
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);}
}
}
EXAMPLE: (READING FROM FILE)
import java.io.*;
class Test{
public static void main(String
args[]){
try{

Unit-I
FileInputStream fin=new
FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e)
{System.out.println(e);}
}
}
 SEQUENCEINPUTSTREAM 
import java.io.*;  
class Simple{  
  public static void main(String args[])
throws Exception{  
   FileInputStream fin1=new FileInputStr
eam("f1.txt");  
   FileInputStream fin2=new FileInputStr

Unit-I
eam("f2.txt");  
   SequenceinputStream sis=new Sequ
enceinputStream(fin1,fin2);  
   int i;  
   while((i=sis.read())!=-1){  
    System.out.println((char)i);  
   }  
   sis.close();  
   fin1.close();  
   fin2.close();  
  }  
}  
Note:reads content fron File1 then from
File2
PRINTSTREAM
import java.io.*;  
class PrintStreamTest
{  
 public static void main(String args
[])throws Exception

Unit-I
{    FileOutputStream fout=new File
OutputStream("mfile.txt");  
  
 PrintStream pout=new PrintStrea
m(fout);  
    pout.println(1900);  
    pout.println("Hello Java");  
    pout.println("Welcome to Java");  
    pout.close();  
    fout.close();  
      
 }  
}   
REFER PROGRAM

Unit-I
IO PIPE(INPUT AND OUTPUT STEAM)
 provides the ability for two threads running in the same JVM to
communicate.
Example:
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeExample {

public static void main(String[] args) throws IOException {


final PipedOutputStream output = new PipedOutputStream();
final PipedInputStream input = new PipedInputStream(output);

Unit-I
Thread thread1 = new Thread(new Runnable() { //thread 1
@Override
public void run() {
try {
output.write("Hello world, pipe!".getBytes());
} catch (IOException e) {
}
} });
Thread thread2 = new Thread(new Runnable() { // thread 2
@Override
public void run() {
try {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
} catch (IOException e) {
} } });

thread1.start();
thread2.start();

}
DATA INPUT/OUTPUT STEAM
 support binary I/O of primitive data type values
(boolean, char, byte, short, int, long, float, and double) as well as
String values

import java.io.*;

public class PipeExample {

public static void main(String[] args) throws IOException {

Unit-I
DataOutputStream output = new DataOutputStream(
new FileOutputStream("f1.data"));

output.write(45); //byte data


output.writeInt(4545); //int data
output.writeDouble(109.123); //double data
//System.out.println((char)output.write(45));
output.close();

DataInputStream input = new DataInputStream(


new FileInputStream("f1.datas"));

int aByte = input.read();


int anInt = input.readInt();
float aFloat = input.readFloat();
double aDouble = input.readDouble();
//etc.
System.out.println(int);
input.close();

}
}
Unit-I
CHARACTER STREAM
FILEWRITER
Constructor Description
FileWriter(String file) creates a new file. It
gets file name in
string.
FileWriter(File file) creates a new file. It
gets file name in File
object.
Methods

Unit-I
Method Description
1) public void write(String writes the string into
text) FileWriter.
2) public void write(char writes the char into
c) FileWriter.
3) public void write(char[] writes char array into
c) FileWriter.
4) public void flush() flushes the data of
FileWriter.
5) public void close() closes FileWriter.
EXAMPLE
import java.io.*;  
class Simple{  
 public static void main(String ar
gs[]){  
  try{  

Unit-I
   FileWriter fw=new FileWriter("ab
c.txt");  
   fw.write("my name is sachin");  
   fw.close();  
  }catch(Exception e)
{System.out.println(e);}  
  System.out.println("success");  
 }  
}  
OUTPUT:
success
FILEREADER

Constructor Description
FileReader(String file) It gets filename in
string. It opens the
given file in read
mode. If file doesn't
exist, it throws
FileNotFoundException.
FileReader(File file) It gets filename in file
instance. It opens the
given file in read

Unit-I
mode. If file doesn't
exist, it throws
FileNotFoundException.

Methods

Method Description

1) public int read() returns a character in


ASCII form. It returns
-1 at the end of file.

2) public void close() closes FileReader.


EXAMPLE
import java.io.*;  
class Simple{  
 public static void main(String ar
gs[])throws Exception{  
  FileReader fr=new FileReader("ab
c.txt");  

Unit-I
  int i;  
  while((i=fr.read())!=-1)  
  System.out.println((char)i);  
  
  fr.close();  
 }  
}  
Output:
my name is sachin
 used to write data to multiple files.
CHARARRAYWRITER

 implements the Appendable interface.

 Its buffer automatically grows when data is


written in this stream
Example:
import java.io.*;  
class Simple{  
 public static void main(String args[])throws Ex

Unit-I
ception{  
  
  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");  
  out.writeTo(f1);  
  out.writeTo(f2);  
  out.writeTo(f3);  
  f1.close();  
  f2.close();  
  f3.close();   }  
}  
READING/WRITING CONSOLE(USER INPUT)

System.in BufferedReader
(supports BufferedInput)

Syntax:

Unit-I
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in)

Read from Console


Convert Byte to char
CHARACTER
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException
{
char c;

Unit-I
BufferedReader br = new
BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = br.read();
System.out.println(c);
} while(c != 'q');
}
}
EXAMPLE:READING STRING
import java.io.*;
class TinyEdit {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];

Unit-I
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
}
WRITING CONSOLE OUTPUT:

System.out.write(“hello”);

System.err.println(“error message”);

System.out.println(“hello”);

Unit-I
PrinterWriter():
 Under Writer class

PrinterWriter(OutputStream
outputstream,boolean
flushOnNewline);
Syntax:
PrinterWriter pw=new
PrinterWriter(System.out,true);
EXAMPLE:
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new
PrintWriter(System.out, true);
pw.println("This is a string");

Unit-I
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
SCANNER CLASS
 Introduced in JDK 5 under java.util package
 Used for getting input from user(text,primitives)
 Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.

METHODS DESCRIPTION
public String next() it returns the next token
from the scanner.

Unit-I
public String nextLine() it moves the scanner
position to the next line
and returns the value as
a string.
public byte nextByte() it scans the next token
as a byte.
public short nextShort() it scans the next token
as a short value.
public int nextInt() it scans the next token
as an int value.
public String next() it returns the next token from
the scanner.
public String nextLine() it moves the scanner position
to the next line and returns the
value as a string.
public byte nextByte() it scans the next token as a
byte.
EXAMPLE:

import java.util.Scanner;
class ScannerTest{
public static void main(String args[])
{
Scanner sc=new
Scanner(System.in);

Unit-I
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();
USING DELIMITER
import java.util.*;
public class ScannerTest{
public static void main(String
args[]){
String input = "10 tea 20 coffee
30 tea buiscuits";

Unit-I
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();
}}
FROM CONSOLE
import java.io.*;  
class ReadStringTest{  
public static void main(String ar
gs[]){  

Unit-I
Console c=System.console();  

System.out.println("Enter your n
ame: ");  
String n=c.readLine();  

System.out.println("Welcome "+
n);  
}  
}  
COMPRESSING USING DEFLATEROUTPUTSTREAM CLASS:
 used to compress the data in the deflate compression
format and povides facility to the other compression
filters, such as GZIPOutputStream.
import java.io.*;
import java.util.zip.*;
class Compress{
public static void main(String args[]){

Unit-I
try{
FileInputStream fin=new FileInputStream("A.java");

FileOutputStream fout=new FileOutputStream("f2.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");
}
}
OUTPUT

Unit-I
File A.java is compressed in File f2.txt
UNCOMPRESSING FILE USING
INFLATERINPUTSTREAM CLASS
 used to uncompress the file in the deflate compression
format and provides facility to the other
uncompression filters, such as GZIPInputStream class.
Example:
import java.io.*;
import java.util.zip.*;
class UnCompress{

Unit-I
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f2.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");
}}
OUTPUT

Unit-I
Compressed file A.java in f2.txt is
uncompressed in D.java
SERIALIZATION
 mechanism of writing the state of an
object into a byte stream.
 String class and all the wrapper
classesimplements
java.io.Serializable  interface by default.
Constructor:
PublicObjectOutputStream(OutputStrea

Unit-I
m out) throws IOException {}

Method Description

1) public final void writes the specified object


writeObject(Object obj) to the
throws IOException {} ObjectOutputStream.

2) public void flush() flushes the current output


throws IOException {} stream.

3) public void close() closes the current output


throws IOException {} stream.
Example:
Student.java
import java.io.Serializable;

Unit-I
public class Student implements
Serializable{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
}
Persist.java
import java.io.*;
class Persist{
public static void main(String
args[])throws Exception{
Student s1 =new
Student(211,"ravi");

Unit-I
FileOutputStream fout=new
FileOutputStream("f.txt");
ObjectOutputStream out=new
ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
DESERIALIZATION

Constructor:
public
ObjectInputStream(InputStream
in) throws IOException {}

Methods

Unit-I
Method Description

1) public final Object reads an object from the


readObject() throws input stream.
IOException,
ClassNotFoundException{}

2) public void close() closes ObjectInputStream.


throws IOException {}
EXAMPLE:

import java.io.*;  
class Depersist{  
 public static void main(String ar
gs[])throws Exception{  
    
  ObjectInputStream in=new Objec

Unit-I
tInputStream(new FileInputStrea
m("f.txt"));  
  Student s=(Student)in.readObject
();  
  System.out.println(s.id+" "+s.na
me);  
  in.close();  
 }  
}  
Output:
211 ravi

You might also like