[go: up one dir, main page]

0% found this document useful (0 votes)
8 views68 pages

6-File handling-13-11-2024 (1)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 68

Module - 6

Java IO Packages
Introduction
• 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.
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
Output Stream& Input stream
• Java application uses an output stream to write
data to a destination, it may be a file, an array,
peripheral device or socket.

• Java application uses an input stream to read


data from a source, it may be a file, an array,
peripheral device or socket.
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.
Useful methods of OutputStream

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

Class
InputStream class is an abstract class. It is the
superclass of all classes representing an input
stream of bytes.
Method Description
reads the next byte of data from the
1) public abstract int read()throws
input stream. It returns -1 at the end of
IOException
file.
returns an estimate of the number of
2) public int available()throws
bytes that can be read from the current
IOException
input stream.
is used to close the current input
3) public void close()throws IOException
stream.
Java File Class

• The File class is an abstract representation of


file and directory pathname. A pathname can
be either absolute or relative.
• The File class have several methods for
working with directories and files such as
creating new directories or files, deleting and
renaming directories or files, listing the
contents of a directory etc.
File Constructor
Constructor Description
It creates a new File instance from a
File(File parent, String child) parent abstract pathname and a child
pathname string.
It creates a new File instance by
File(String pathname) converting the given pathname string into
an abstract pathname.
It creates a new File instance from a
File(String parent, String child) parent pathname string and a child
pathname string.
It creates a new File instance by
File(URI uri) converting the given file: URI into an
abstract pathname.
Methods of File Class
Modifier and Type Method Description
It creates an empty file in the
createTempFile(String prefix, default temporary-file
static File
String suffix) directory, using the given prefix
and suffix to generate its name.
It atomically creates a new,
empty file named by this
boolean createNewFile() abstract pathname if and only
if a file with this name does not
yet exist.
It tests whether the application
boolean canWrite() can modify the file denoted by
this abstract pathname.String[]
It tests whether the application
boolean canExecute() can execute the file denoted by
this abstract pathname.
It tests whether the
application can read the
boolean canRead()
file denoted by this
abstract pathname.
It tests whether this
boolean isAbsolute() abstract pathname is
absolute.
It tests whether the file
boolean isDirectory() denoted by this abstract
pathname is a directory.
It tests whether the file
boolean isFile() denoted by this abstract
pathname is a normal file.
It returns the name of the
String getName() file or directory denoted by
this abstract pathname.
It returns the pathname
string of this abstract
String getParent() pathname's parent, or null
if this pathname does not
name a parent directory.
It returns a java.io.file.Path object
Path toPath() constructed from the this abstract
path.
It constructs a file: URI that
URI toURI()
represents this abstract pathname.
It returns an array of abstract
pathnames denoting the files in the
File[] listFiles()
directory denoted by this abstract
pathname
It returns the number of unallocated
long getFreeSpace() bytes in the partition named by this
abstract path name.
It returns an array of strings naming
the files and directories in the
String[] list(FilenameFilter filter) directory denoted by this abstract
pathname that satisfy the specified
filter.
It creates the directory named by this
boolean mkdir()
abstract pathname.
• import java.io.*;
• class File1
• {
• public static void main(String[] args) {

• try {
• File f = new File("firstfile.txt");
• if (f.createNewFile()) {
• System.out.println("New File is created!");
• } else {
• System.out.println("File already exists.");
• }
• } catch (IOException e) {
• System.out.println(e);
• }

• }
• }
• // to list all the file in the directoryjav
• import java.io.*;
• class File2
• {
• public static void main(String[] args)
• {
• File f=new File("C:/users/admin/desktop/java/");
• String filenames[]=f.list();
• for(String filename:filenames){
• System.out.println(filename);
• }
• }
• }
Implementation of …
• 1. Byte stream
• 2. Character stream
• 3. Buffered stream
• 4. Data stream
• 5. Object Stream
Byte stream in java
• 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 −
File input/output stream
• 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 ______________class.
• Java FileOutputStream is an output stream
used for writing data to a _________
FileOutputStream Methods
Method Description
It is used to clean up the connection with the
protected void finalize()
file output stream.
It is used to write ary.length bytes from the byte
void write(byte[] ary)
array to the file output stream.
It is used to write len bytes from the byte array
void write(byte[] ary, int off, int len)
starting at offset off to the file output stream.
It is used to write the specified byte to the file
void write(int b)
output stream.
It is used to return the file channel object
FileChannel getChannel()
associated with the file output stream.
It is used to return the file descriptor associated
FileDescriptor getFD()
with the stream.
void close() It is used to closes the file output stream.
Sample program using FileOutputStream
• import java.io.*;
• class Simplewrite
• {
• public static void main(String ar[])
• {
• try
• {
• FileOutputStream f = new FileOutputStream (“abc.txt");
• //f.write(45);
• String s = "This the Fileoutputstream program";
• byte b[] = s.getBytes(); // convert the string in to byte array
• f.write(b);
• f.close();
• }catch(Exception e)
• {
• System.out.println(e);
• }
• }
• }
• Note: to check the output see that a file called abc.txt is created in the path where you
executed this program
Java FileInputStream class methods
Method Description

It is used to return the estimated number of


int available() bytes that can be read from the input stream.

It is used to read the byte of data from the


int read() input stream.

int read(byte[] b) It is used to read up to b.length bytes of data


from the input stream.

int read(byte[] b, int off, int len) It is used to read up to len bytes of data from
the input stream.

long skip(long x) It is used to skip over and discards x bytes of


data from the input stream.

It is used to return the unique FileChannel


FileChannel getChannel() object associated with the file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

It is used to ensure that the close method is


protected void finalize() call when there is no more reference to the
file input stream.
void close() It is used to closes the stream.
Example of FileInputStream class
Java FileInputStream class obtains input bytes from a file FileOutputStream
import java.io.*;
class Simpleread
{
public static void main(String ar[])
{
try
{
FileInputStream f = new FileInputStream(“abc.txt");
int i = 0;
int i=f.read();
System.out.print((char)i);
while((i=f.read())!= -1)
{
System.out.print((char)i);
}
f.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
• import java.io.*;
• public class filestream {

• public static void main(String args[]) {



• try {
• byte b [] = {11,21,3,40,5};
• OutputStream os = new FileOutputStream("test.txt");
• for(int x = 0; x < b.length ; x++) {
• os.write( b[x] ); // writes the bytes
• }
• os.close();

• InputStream is = new FileInputStream("test.txt");
• int size = is.available();

• for(int i = 0; i < size; i++) {


• System.out.print((char)is.read() + " ");
• }
• is.close();
• } catch (IOException e) {
• System.out.print("Exception");
• }
• }
• }
Data Input/output Stream
A data input stream enable an application read primitive Java data types
from an underlying input stream in a machine-independent way(instead
of raw bytes). That is why it is called DataInputStream – because it
reads data (numbers) instead of just bytes.
DataInputStream Class
• import java.io.*;
• class Datain
• {
• public static void main(String[] args) throws IOException
• {
• FileInputStream in = new FileInputStream("sample.txt");
• DataInputStream di = new DataInputStream(in);
• int count = in.available();
• byte[] ary = new byte[count];
• in.read(ary);
• for (byte bt : ary)
• {
• char k = (char) bt;
• System.out.print(k);
• }
• }
• }
Java DataOutputStream Class

• Java DataOutputStream class allows an


application to write primitive Java data types
to the output stream in a machine-
independent way.
• Java application generally uses the data
output stream to write data that can later be
read by a data input stream.
• import java.io.*;
• public class Dataout
• {
• public static void main(String[] args) throws IOException
• {
• FileOutputStream f = new FileOutputStream("Sample.txt");
• DataOutputStream data = new DataOutputStream(f);
• data.writeChars("This is Dataoutputstream

• programming");
• data.flush();
• data.close();
• System.out.println("Success...");
• }
• }
Buffered Stream
• Java BufferedInputStream Class
• Java BufferedInputStream class is used to read information from stream. It
internally uses buffer mechanism to make the performance fast.
The important points about BufferedInputStream are:
• When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a
time.
• When a BufferedInputStream is created, an internal buffer array is created.

• BufferedOutputStream-Java BufferedOutputStream class is used for


buffering an output stream. It internally uses buffer to store data. It adds
more efficiency than to write data directly into a stream. So, it makes the
performance fast.
Java BufferedOutputStream Class

• Java BufferedOutputStream class is used for buffering an


output stream. It internally uses buffer to store data. It adds
more efficiency than to write data directly into a stream. So, it
makes the performance fast.
Java BufferedOutputStream class constructors
• BufferedOutputStream(OutputStream os) - It creates the new
buffered output stream which is used for writing the data to
the specified output stream.
• BufferedOutputStream(OutputStream os, int size) It creates
the new buffered output stream which is used for writing the
data to the specified output stream with a specified buffer
size.
• void write(int b) - It writes the specified byte
to the buffered output stream.
• void write(byte[] b, int off, int len) - It write
the bytes from the specified byte-input stream
into a specified byte array, starting with the
given offset
• void flush() - It flushes the buffered output
stream.
BufferedOutputStream Example
• import java.io.*;
• public class BOS
• {
• public static void main(String args[])throws Exception
• {
• FileOutputStream f=new FileOutputStream("BOS.txt");
• BufferedOutputStream bout=new BufferedOutputStream(f);
• String s="Welcome to Buffered Reader Programming.";
• byte b[]=s.getBytes();
• bout.write(b);
• bout.flush();
• bout.close();
• f.close();
• System.out.println("success");
• }
• }
BufferedInputStream
• Java BufferedInputStream class is used to read
information from stream. It internally uses buffer
mechanism to make the performance fast.
• The important points about BufferedInputStream
are:
• When the bytes from the stream are skipped or
read, the internal buffer automatically refilled from
the contained input stream, many bytes at a time.
• When a BufferedInputStream is created, an internal
buffer array is created.
• BufferedInputStream(InputStream IS) - It
creates the BufferedInputStream and saves it
argument, the input stream IS, for later use.
• BufferedInputStream(InputStream IS, int size)
- It creates the BufferedInputStream with a
specified buffer size and saves it argument,
the input stream IS, for later use.
Methods of Buffered Input Stream
Method Description
It returns an estimate number of bytes
that can be read from the input stream
int available()
without blocking by the next invocation
method for the input stream.
It read the next byte of data from the
int read()
input stream.
It read the bytes from the specified byte-
int read(byte[] b, int off, int ln) input stream into a specified byte array,
starting with the given offset.
It closes the input stream and releases
void close() any of the system resources associated
with the stream.
It repositions the stream at a position
void reset() the mark method was last called on this
input stream.
It sees the general contract of the mark
void mark(int readlimit)
method for the input stream.
It skips over and discards x bytes of data
long skip(long x)
from the input stream.
It tests for the input stream to support
boolean markSupported()
the mark and reset methods.
Mark and reset method in
BufferedInputStream
import java.io.BufferedInputStream; // mark is set on the input stream
import java.io.FileInputStream; bis.mark(0);
import java.io.IOException;
System.out.println("Char : "+
import java.io.InputStream;
(char)bis.read());
public class bufferedinput{ System.out.println("reset()
public static void main(String[] args) throws Exception { invoked");
InputStream iStream = null;
BufferedInputStream bis = null;
// reset is called
try { bis.reset();
// read from file c:/test.txt to input stream
iStream = new
FileInputStream("c:/users/admin/desktop/java/one.tx // read and print characters
t"); System.out.println("char : "+
// input stream converted to buffered input stream
(char)bis.read());
bis = new BufferedInputStream(iStream); System.out.println("char : "+
(char)bis.read());
// read and print characters one by one
System.out.println("Char : "+(char)bis.read());
System.out.println("Char : "+(char)bis.read()); } catch(Exception e)
System.out.println("Char : "+(char)bis.read()); {System.out.println(e);}
}
• import java.io.*;
• public class BufferedInputStreamExample{
• public static void main(String args[]){
• try{
• FileInputStream fin=new
FileInputStream(“c:/users/admin/desktop/java/one.txt");
• BufferedInputStream bin=new BufferedInputStream(fin);
• int i;
• while((i=bin.read())!=-1){
• System.out.print((char)i);
• }
• bin.close();
• fin.close();
• }catch(Exception e){System.out.println(e);}
• }
• }
Buffered Reader/Writer class
• Java.io.BufferedReader class reads text from a character-
input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
• Following are the important points about BufferedReader

• The buffer size may be specified, or the default size may
be used.
• Each read request made of a Reader causes a
corresponding read request to be made of the underlying
character or byte stream.
• The Java.io.BufferedWriter class writes text to
a character-output stream, buffering characters
so as to provide for the efficient writing of
single characters, arrays, and strings.
Following are the important points about
BufferedWriter −
• The buffer size may be specified, or the default
size may be used.
• A Writer sends its output immediately to the
underlying character or byte stream.
Java BufferedReader Class
• Java BufferedReader class is used to read the text
from a character-based input stream. It can be used
to read data line by line by readLine() method. It
makes the performance fast. It inherits Reader class.
• Java BufferedReader class constructors
• BufferedReader(Reader rd) - It is used to create a
buffered character input stream that uses the
default size for an input buffer.
• BufferedReader(Reader rd, int size)- It is used to
create a buffered character input stream that uses
the specified size for an input buffer.
• import java.io.*;
• public class BuffRead
• {
• public static void main(String args[])throws Exception
• {
• InputStreamReader r=new InputStreamReader (System.in);

• BufferedReader br=new BufferedReader(r);


• System.out.println("Enter your Regno and name");
• String name=br.readLine();
• int no = Integer.parseInt(br.readLine());
• System.out.println(" Hello "+name + " " +no);
• }
• }
Buffered Writer
• import java.io.*;
• public class bufferedwriter
• {
• public static void main(String[] args) throws Exception
• {
• FileWriter writer = new FileWriter

• ("c://users/admin/desktop/java/one.txt");
• BufferedWriter buffer = new BufferedWriter(writer);
• buffer.write("Welcome to java File handling

• programming.");
• buffer.close();
• System.out.println("Success");
• }
• }
Character streams
• Java Byte streams are used to perform input and output of 8-bit bytes,

whereas 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 the major difference is that

FileReader reads two bytes at a time and FileWriter writes two bytes at

a time.
Java FileWriter and FileReader
• 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 FileWriter class
• Java FileWriter class is used to write character-
oriented data to the file.
Constructors of FileWriter class:
• 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 of FileWriter
Methods Description

1) public void write(String text) writes the string into FileWriter.

2) public void write(char c) writes the char into FileWriter.

3) public void write(char[] c) writes char array into FileWriter.

4) public void flush() flushes the data of FileWriter.

5) public void close() closes FileWriter.


Java File Reader class
Java FileReader class is used to read data from
the file. It returns data in byte format like
FileInputStream class.
Constructor Description
It gets filename in string. It opens the
FileReader(String file) given file in read mode. If file doesn't
exist, it throws
FileNotFoundException.

It gets filename in file instance. It


FileReader(File file) opens the given file in read mode. If
file doesn't exist, it throws
FileNotFoundException.
Method Description

returns a character in
1) public int read() ASCII form. It returns -
1 at the end of file.

2) public void close() closes FileReader.


• import java.io.*; Read a File
• import java.util.Scanner; // Import the Scanner class to read text files

• public class readfile


• {
• public static void main(String[] args) {
• try {
• File f = new File("one.txt");
• Scanner s = new Scanner(f);
• while (s.hasNextLine()) {
• String data = s.nextLine();
• System.out.println(data);
• }
• s.close();
• } catch (FileNotFoundException e) {
• System.out.println("An error occurred.");

• }
• }
• }
Write To a File

• We used the FileWriter class together with its write()


method to write some text to the file.
• import java.io.FileWriter;
• import java.io.IOException;

• public class writefile


• {
• public static void main(String[] args) {
• try
• {
• FileWriter fw = new FileWriter("one.txt");
• fw.write("First file program to write something on it");
• fw.close();
• System.out.println("Successfully wrote to the file.");
• } catch (Exception e) {
• System.out.println("An error occurred.");
• }
• }
• }
Character stream example

• import java.io.*;
• public class charstream { int c;
while ((c = in.read()) != -
• public static void main(String
1) {
args[]) throws out.write(c);
}
}finally {
• IOException {
if (in != null) {
• FileReader in = null; in.close();
• FileWriter out = null; }
if (out != null) {
• try { out.close();
• in = new }
FileReader("Sample.txt"); }
• out = new }
FileWriter("Sample2.txt"); }

• Similarly go through the rest all Classes such as
• CharArrayReader
• CharArrayWriter
• PrintStream
• PrintWriter
• OutputStreamWriter
• InputStreamReader
• PushbackInputStream
• PushbackReader
• StringWriter
• StringReader
• PipedWriter
• PipedReader
• FilterWriter
• FilterReader
Serialization and Deserialization in Java

• Serialization in Java is a mechanism of writing


the state of an object into a byte stream.
• It is mainly used in Hibernate, RMI, JPA, EJB and
JMS technologies.
• The reverse operation of serialization is called
deserialization.
• Advantages of Java Serialization
• It is mainly used to travel object's state on the
network (which is known as marshaling).
java.io.Serializable interface
• Serializable is a marker interface (has no data member and method). It is
used to "mark" Java classes so that objects of these classes may get the
certain capability.

import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
• import java.io.*;
• class Student implements Serializable{
• int id;
• String name;
• public Student(int id, String name) {
• this.id = id;
• this.name = name;
• }
• }
• class serial
• {
• public static void main(String args[])throws Exception
• {
• Student s1 =new Student(211,"ravi");
• FileOutputStream fout=new FileOutputStream("f.txt");
• ObjectOutputStream out=new ObjectOutputStream(fout);
• out.writeObject(s1);
• out.flush();
• System.out.println("success");
• }
• }
Deserialization in java

• Deserialization is the process of reconstructing


the object from the serialized state.It is the
reverse operation of serialization.
• import java.io.*;
• class Student implements Serializable{
• int id;
• String name;
• public Student(int id, String name) {
• this.id = id;
• this.name = name;
• }
• }
• class deserial
• {
• public static void main(String args[])throws Exception
• {
• ObjectInputStream in=new ObjectInputStream(new

• FileInputStream("f.txt"));
• Student s=(Student)in.readObject();
• System.out.println(s.id+" "+s.name);
• in.close();
• }
• }
//program using serialziation and deserialziation with array of objects

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Scanner;
public class serialdeserial
{
public static void main(String ar[])throws IOException,ClassNotFoundException
{
studentdemo sd[] = new studentdemo[3];
System.out.println("enter the details");
Scanner s =new Scanner(System.in);
String name,course;
ObjectOutputStream objout = new ObjectOutputStream(new FileOutputStream("student.txt"));
for(int i=0;i<sd.length;i++)
{
System.out.println("Enter name and course");
name= s.nextLine();
course=s.nextLine();
sd[i]= new studentdemo(name,course);
objout.writeObject(sd[i]);
}
objout.writeObject(new reading());
objout.close();
ObjectInputStream objin = new ObjectInputStream(new FileInputStream("student.txt"));
Object obj=null;
System.out.println("the data from the file -deserialization");
• while((obj=objin.readObject()) instanceof reading ==false)
• {
• System.out.println(((studentdemo)obj).name+" "+((studentdemo)obj).course);
• }
• objin.close();
• }

• }

• class studentdemo implements Serializable


• {
• String name;
• String course;

• public studentdemo(String name,String course)
• {
• this.name=name;
• this.course=course;
• }
• }

• class reading implements Serializable


• {

• }
END

You might also like