Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Amity School of Engineering &

Technology
B.Tech CSE, Semester 5
Java IO (Unit 3)
Dr. Dolly Sharma

1
Overview
• IO provides communication with devices (files, console, networks
etc.)
• Communication varies (sequential, random-access, binary, char,
lines, words, objects, …)
• Java provides a “mix and match” solution based around byte-
oriented and character-oriented I/O streams – ordered
sequences of data (bytes or chars).
• System streams System.in, (out and err) are available to all Java
programs (console I/O) – System.in is an instance of the
InputStream class, System.out is an instance of PrintStream
• So I/O involves creating appropriate stream objects for your task.

Department of Computer Science 2


The IO Zoo
• More than 60 different stream types.
• Based around four abstract classes: InputStream,
OutputStream, Reader and Writer.
• Unicode characters (two bytes per char) are dealt
separately with Reader/Writers (and their
subclasses).
• Byte oriented I/O is dealt with by InputStream,
OutputStream and their subclasses.

Department of Computer Science 3


• Java application uses an input stream to read data
from a source; it may be a file, an array, peripheral
device or socket.

Department of Computer Science 4


Reading Bytes
• Abstract classes provide basic common operations which are
used as the foundation for more concrete classes, eg InputStream
has
• int read( ) - reads a byte and returns it or –1 (end of input)
• int available( ) – num of bytes still to read
• void close()
• Concrete classes override this method, eg FileInputStream reads
one byte from a file, System.in is a subclass of InputStream that
allows you to read from the keyboard

Department of Computer Science 5


InputStream hierarchy

Department of Computer Science 6


Method Description

1) public abstract int read()throws reads the next byte of data from
IOException the input stream. It returns -1 at
the end of the file.
2) public int available()throws returns an estimate of the number
IOException of bytes that can be read from the
current input stream.
3) public void close()throws is used to close the current input
IOException stream.

Department of Computer Science 7


Writing Bytes
• void write(int b) - writes a single byte to
an output location.
• Java IO programs involve using concrete
versions of these because most data
contain numbers, strings and objects
rather than individual bytes

Department of Computer Science 8


OutputStream Hierarchy

Department of Computer Science 9


Method Description

1) public void write(int)throws is used to write a byte to the


IOException current output stream.
2) public void write(byte[])throws is used to write an array of byte to
IOException the current output stream.
3) public void flush()throws flushes the current output stream.
IOException
4) public void close()throws is used to close the current output
IOException stream.

Department of Computer Science 10


File Processing
• Typical pattern for file processing is:
• OPEN A FILE
• CHECK FILE OPENED
• READ/WRITE FROM/TO FILE
• CLOSE FILE
• Input and Output streams have close method
(output may also use flush)

Department of Computer Science 11


1.import java.io.FileOutputStream;
2.public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
6. fout.close();
7. System.out.println("success...");
8. }catch(Exception e){System.out.println(e);}
9. } Output:
10.}
Success...
The content of a text file testout.txt is set with the data A.

testout.txt

A Department of Computer Science 12


1.import java.io.FileOutputStream;
2.public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

6. String s="Welcome";
7. byte b[]=s.getBytes();//converting string into byte array
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){System.out.println(e);}
12. }
Output:
13.}
Success...

testout.txt

Department of Computer Science Welcome 13


File IO Streams
• FileInputStream and FileOutputStream give you IO from a
disk file
• FileInputStream fin = new FileInputStream(“in.txt”);
• We can now read bytes from a file but not much else! To get
a file stream that can process data means combining two
streams into a filtered stream (here using DataInputStream):
• FileInputStream fin = new FileInputStream(“in.txt”);
• DataInputStream din = new DataInputStream(fin);
• double s = din.readDouble(); // better interface to file!

Department of Computer Science 14


Java FileInputStream
Class
• Java FileInputStream class obtains input bytes from
a file. It is used for reading byte-oriented data
(streams of raw bytes) such as image data, audio,
video etc. You can also read character-stream data.
But, for reading streams of characters, it is
recommended to use FileReader class.

Department of Computer Science 15


1.import java.io.FileInputStream;
2.public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }

Department of Computer Science 16


1.package com.javatpoint;
2.
3.import java.io.FileInputStream;
4.public class DataStreamExample {
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("D:\\testout.txt");

8. int i=0;
9. while((i=fin.read())!=-1){
10. System.out.print((char)i);
11. }
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }

Department of Computer Science 17


Buffering
• By default streams are not buffered, so every read or write results in
a call to the OS (= very slow!).
• Adding buffering means chaining streams:
DataInputStream din =
new DataInputStream(new BufferedInputStream(new FileInputStream
(“in.txt”)));
• DataInputStream is last in the chain here because we want to use its
methods and we want them to use the buffered methods (eg read).

Department of Computer Science 18


File I/O Streams
Constructors
• FileInputStream(String name)
• FileOutputStream(String name)
• BufferedInputStream(InputStream in)
• BufferedOutputStream(OutputStream out)

Department of Computer Science 19


1.import java.io.*;
2.public class BufferedOutputStreamExample{
3.public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("D:\\testout.txt
");
5. BufferedOutputStream bout=new BufferedOutputStream(fout)
;
6. String s="Welcome to javaTpoint.";
7. byte b[]=s.getBytes();
8. bout.write(b);
9. bout.flush();
10. bout.close();
11. fout.close();
12. System.out.println("success");
13.}
14.}

Department of Computer Science 20


1.import java.io.*;
2.public class BufferedInputStreamExample{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");

6. BufferedInputStream bin=new BufferedInputStream(fin);


7. int i;
8. while((i=bin.read())!=-1){
9. System.out.print((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15.}

Department of Computer Science 21


FileReader Class
• java.io.FileReader
• Associated with File object
• Translates data bytes from File object into a
stream of characters.
• used to read data from the file. It returns data in
byte format like FileInputStream class.
• Constructors
• FileReader( <File object> );
• Methods
• read(), readLine()
• close()
1.package com.javatpoint;
2. import java.io.FileReader;
3.public class FileReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\testout.txt");
6. int i;
7. while((i=fr.read())!=-1)
8. System.out.print((char)i);
9. fr.close();
10. }
11.}

Department of Computer Science 23


import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class LineNumberer{


public static void main(String[] args){
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inFile = console.next();
System.out.print("Output file: ");
String outFile = console.next();
try{
FileReader reader = new FileReader(inFile);
Scanner in = new Scanner(reader);
PrintWriter out = new
PrintWriter(outputFileName);
int lineNumber = 1;

while (in.hasNextLine()){
String line = in.nextLine();
out.println("/* " + lineNumber + " */ " +
line);
lineNumber++;
}

out.close();
} catch (IOException exception){
System.out.println("Error processing file: "
+ exception);
}
}
}
FileWriter Class
• java.io.FileWriter
• Associated with File object
• Connects an output stream to write bytes of info
• Java FileWriter class is used to write character-oriented data to a file.
It is character-oriented class which is used for file handling in java.
• Unlike FileOutputStream class, you don't need to convert string into
byte array because it provides method to write string directly.
• Constructors
• FileWriter( <filename>, <boolean> );
• true to append data, false to overwrite all of file
• This will overwrite an existing file
• To avoid, create File object and see if exists() is true
1.package com.javatpoint;
2.import java.io.FileWriter;
3.public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");

7. fw.write("Welcome to javaTpoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12.} Department of Computer Science 27
Java File Output
• PrintWriter
• composed from several objects
PrintWriter out =
new PrintWriter(
new FileWriter( dstFileName, false ), true );
• requires throws FileNotFoundException,
which is a sub class of IOException

• Methods
• print(), println(): buffers data to write
• flush(): sends buffered output to destination
• close(): flushes and closes stream
Java File Output
// With append to an existing file
PrintWriter outFile1 =
new PrintWriter(
new FileWriter(dstFileName,true),false);

// With autoflush on println


PrintWriter outFile2 =
new PrintWriter(
new FileWriter(dstFileName,false),true);

outFile1.println( “appended w/out flush” );


outFile2.println( “overwrite with flush” );
To flush or not to flush
• Advantage to flush:
• Safer – guaranteed that all of our data will write to the
file

• Disadvantage
• Less efficient – writing to file takes up time, more
efficient to flush once (on close)
Extras!!

Department of Computer Science 31


Java
SequenceInputStream
Class

Java SequenceInputStream class is used to read data


from multiple streams. It reads data sequentially
(one by one).

Department of Computer Science 32


Java
SequenceInputStream
Class
1.import java.io.*;
2.class InputStreamExample {
3. public static void main(String args[])throws Exception{
4. FileInputStream input1=new FileInputStream("D:\\testin.txt");

5. FileInputStream input2=new FileInputStream("D:\\testout.txt");

6. SequenceInputStream inst=new SequenceInputStream(input1, in


put2);
7. int j;
8. while((j=inst.read())!=-1){
9. System.out.print((char)j);
10. }
testin.txt:
11. inst.close(); Welcome to Java IO Programming.
12. input1.close(); testout.txt:
13. input2.close(); It is the example of Java SequenceInputStream class.
14. }
Department of Computer Science 33
15.}
Example that reads the
data from two files and writes
into another file
1.class Input1{
2. public static void main(String args[])throws Exception{
3. FileInputStream fin1=new FileInputStream("D:\\testin1.txt");
4. FileInputStream fin2=new FileInputStream("D:\\testin2.txt");
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
SequenceInputStream sis=new SequenceInputStream(fin1,fin2);
6. int i;
7. while((i=sis.read())!=-1) {
8. fout.write(i); }
9. sis.close();
10. fout.close();
11. fin1.close();
12. fin2.close();
13. System.out.println("Success.."); }}

Department of Computer Science 34


Java
ByteArrayOutputStream Class
• Java ByteArrayOutputStream class is used to write
common data into multiple files. In this stream, the
data is written into a byte array which can be
written to multiple streams later.
• The ByteArrayOutputStream holds a copy of data
and forwards it to multiple streams.
• The buffer of ByteArrayOutputStream
automatically grows according to data.

Department of Computer Science 35


Java
ByteArrayOutputStream Class

Department of Computer Science 36


Java
ByteArrayOutputStream Class
import java.io.*;
public class DataStreamExample {
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(65);
Output:
bout.writeTo(fout1); Success...
bout.writeTo(fout2); f1.txt:
A
bout.flush(); f2.txt:
bout.close();//has no effect A
System.out.println("Success..."); }
Department of Computer Science
} 37
Java ByteArrayInputStream
• The ByteArrayInputStream is composed of two
words: ByteArray and InputStream. As the name
suggests, it can be used to read byte array as input
stream.
• Java ByteArrayInputStream class contains an
internal buffer which is used to read byte array as
stream. In this stream, the data is read from a byte
array.
• The buffer of ByteArrayInputStream automatically
grows according to data.

Department of Computer Science 38


Java ByteArrayInputStream
import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0; Output:
ASCII value of Character is:35; Special character is: #
while ((k = byt.read()) != -1) { ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special charact
er is: " + ch); } } }

Department of Computer Science 39


DataOutputStream

The DataOutputStream stream lets you write the primitives to


an output source.

• public final void write(byte[] w, int off, int len)throws


IOException
• Writes len bytes from the specified byte array starting at point off,
to the underlying stream.

• Public final int write(byte [] b)throws IOException


• Writes the current number of bytes written to this data
output stream. Returns the total number of bytes written
into the buffer.
Department of Computer Science 40
DataOutputStream
(a) public final void writeBooolean()throws
IOException,
(b) public final void writeByte()throws IOException,
(c) public final void writeShort()throws IOException
(d) public final void writeInt()throws IOException
• These methods will write the specific primitive type
data into the output stream as bytes.

Department of Computer Science 41


DataOutputStream
import java.io.*;
public class DataInput_Stream {
public static void main(String args[])throws IOException {
// writing string to a file encoded as modified UTF-8
DataOutputStream dataOut = new DataOutputStream(new
FileOutputStream("E:\\file.txt"));
dataOut.writeUTF("hello");
// Reading data from the same file
DataInputStream dataIn = new DataInputStream(new
FileInputStream("E:\\file.txt"));
while(dataIn.available()>0) {
String k = dataIn.readUTF();
System.out.print(k+" "); } } }
Department of Computer Science 42
Random Access Streams
• Files are normally processed from start to end but this can
be time consuming (recall that streams are sequences of
bytes). To find (or write) data anywhere in a file we can use
a RandomAccessFile stream class.
• RandomAccessFile in = new RandomAccessFile(“in.dat”,”r”);
• RandomAccessFile out = new
RandomAccessFile(“out.dat”,”rw”);
• A useful method is “seek(long pos)” that allows you to move
the file pointer to a byte position in the file and start
reading from there

Department of Computer Science 43


Random Access Streams
• A random access file behaves like a large array of
bytes.
• There is a cursor implied to the array called
file pointer, by moving the cursor we do the read
write operations.
• If end-of-file is reached before the desired number
of byte has been read than EOFException is thrown.
It is a type of IOException.

Department of Computer Science 44


Random Access Streams
1.import java.io.IOException;
2.import java.io.RandomAccessFile;
3.
4.public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }

Department of Computer Science 45


Random Access Streams
1. private static byte[] readFromFile(String filePath, int position, int size)
2. throws IOException {
3. RandomAccessFile file = new RandomAccessFile(filePath, "r");
4. file.seek(position);
5. byte[] bytes = new byte[size];
6. file.read(bytes);
7. file.close();
8. return bytes;
9. }
10. private static void writeToFile(String filePath, String data, int position)
11. throws IOException {
12. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
13. file.seek(position);
14. file.write(data.getBytes());
15. file.close();
16. }
17.}

Department of Computer Science 46

You might also like