6.Managing InputOutput Files in Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

6.

Managing Input/Output/Files in Java

6.1Introduction and Concept of Streams


--Stream is a sequence of bytes which come inside
the program called as input stream or goes from
program is called as output stream.
--Input Stream is used to read data from source
while output stream is used to write data in the
source.
--Stream is encapsulated by java under
java.io.package. Java defines two types of
streams .They are
I)Byte Stream:It provides a convinient way to
handle input and output in the form of bytes.
II)Chracter Stream:It provides a convinient way
to handle input and output in the form of chracters.
6.2.Stream Classes:Byte Stream Classes
--The use of Byte Stream Classes is to read data in byte format from an input
stream and write data in byte format to an output stream.
--byte stream classes are divided into two groups:
1.InputStream Classes:
--These classes are extended from InputStream which is an abstract class.
--These classes are used to read bytes from source such as Files ,memory or
console.

1.OutputStream Classes:
--These classes are extended from OutputStream which is an abstract class.
--These classes are used to write bytes from source such as Files ,memory or
console.
Source Destination

|| | |
Bytes are || | |
read from || | |Bytes are
Source using || | | Written to

| |_ _ _ _ _ _ _| | destination
using
Program
|_ _ _ _ _ ____ | OutputStream
classes
6.2.Stream Classes:Byte Stream Classes
6.2.1.InputStream class
--InputStream class is a parent class for all the classes which have main functionality to
read bytes from a file ,memory or console.
--it is not allowed to create an object of InputStream class since it is an abstract class
but it is possible to use its child classes for the purpose of reading bytes from the
input stream.
InputStream

PipedInputStream ByteArrayInputStream

ObjectInputStream FilterInputStream

FilterINputStream

DataInputStream BufferedInputStream
Methods of InputStream Class

Methods Description

int available() Returns the total number of bytes which the input stream
can read.

abstract int read() Reads the next byte of the input stream in integer format.

int read(byte[]b) Reads a bunch of bytes from the input stream and store
them in the form of byte array.

close() Closes the input stream and also does the task of freeing
any resources which are connected with input stream.
6.2.2.OutputStream Classes
--OutputStream class is a parent class for all the classes which have main
functionality to write bytes from a file ,memory or console.
--it is not allowed to create an object of OutputStream class since it is an
abstract class but it is possible to use its child classes for the purpose of
writing bytes from the input stream.

OutputStream

PipedOutputStream ByteArrayOutputStream

ObjectOutputStream FilterOutputStream

FilterOutputStream

DataOutputStream BufferedInputStream
Methods of OutputStream
Methods Description

flush() Flushes the output stream and clear the buffer.

abstract write(int c) Writes byte into the output stream.

write(byte[]b) Write entire byte array to the output stream.

close() Closes the output stream and also does the task of
freeing any resources which are connected with output
stream.
Implementation Of Byte Stream Classes
A.ByteArrayInputStream & ByteArrayOutputStream
--The ByteArrayInputStream and ByteArrayOutputStream classes read data from and write
data to byte array in memory,respectively.
import java.io.ByteArrayInputStream;
public class ByteArrayEx1
{
public static void main(String[]arg)
{
String msg="Handling data in Byte format";

ByteArrayInputStream bs=new ByteArrayInputStream(msg.getBytes());


int ch;
while((ch=bs.read())!=-1)
{
System.out.println((char)ch);
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayEx2
{
public static void main(String[]args) throws IOException
{
String s1="Handling Data";
String s2="in Byte Format";
ByteArrayOutputStream bs=new ByteArrayOutputStream();
bs.write(s1.getBytes());
bs.write(s2.getBytes());
System.out.println(bs.toString());

}
}
6.3.Creation of files,Reading/writing Characters,Reading/Writing
Bytes.
1)FileInputStream
--java.io.FileInputStream reads byte stream from a file system.It has three Constructors:
i)FileInputStream(File file):Accepts File Objects.
ii)FileInputStream(FileDescriptor fdobj):Accepts FileDescriptor object.
iii)FileInputStream(String name):Accepts file path as String.
Methods of FileInputStream class
Methods Description

int available() Returns the estimated number of bytes that can be read from
the input stream.
int read() Reads the byte of the data from the input stream.

int read(byte[]b) Read up to b.length bytes of data from the input stream.

long skip(long x) Skip over and discards x bytes of data from the input stream.

void close() Closes the stream.


import java.io.*;
public class FileEx1
{
public static void main(String[]args)throws IOException
{
File file=new File(“t1.txt");
FileInputStream fis=new FileInputStream(file);
int i=0;
while((i=fis.read())!=-1)
{
System.out.println((char)i);
}
System.out.println("\n\n");
fis.close();
fis=new FileInputStream(file);
byte[]b=new byte[256];
while((i=fis.read(b))!=-1)
{
System.out.println(new String(b));
}
fis.close();
}
}
import java.io.*;
public class FileEx2
{
public static void main(String[]args)throws IOException
{
File file=new File("p1.txt");
FileInputStream fis=new FileInputStream(file);
int i=0,j=0,n;
n=Integer.parseInt(args[0]);
while((i=fis.read())!=-1)
{
if(i%n==0)
{
System.out.println((char)i);
}
j++;
}
System.out.println("\n\n");
fis.close();
fis.close();
}
}
2)FileOutputStream
--java.io.FileOutputStream writes byte stream into a file system.It has following
constructors:
i)FileOutputStream(File file):Accepts file object.
ii)FileOutputStream(File file,boolean append):Accepts file object and a boolean
variable to append.
iii)FileOutputStream(FileDescriptor fdObj):Accepts FileDescriptor Object.
iv)FileOutputStream(String name):Accepts file path as string.
v)FileOutputStream(String name,boolean append):Accepts file path as string and a
Boolean variable to append.
import java.io.*;
public class FileEx13
{
public static void main(String[]args)throws IOException
{
File file=new File("p1.txt");
FileOutputStream fos=new FileOutputStream(file);
fos.write("Welcome to my web".getBytes());
fos.write("Welcome to my Web".getBytes());
byte[]b="Welcome to my web".getBytes();
for(int i=0;i<b.length;i++)
{
fos.write(b[i]);
}
fos.close();
System.out.println("Data written in a file:");
}
}
import java.io.*;
public class FileEx42
{
public static void main(String[]args)throws IOException
{
int n=5;
String str;
File file=new File(“d1.txt");
FileOutputStream fos=new FileOutputStream(file);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

for(int i=0;i<n;i++)
{
System.out.println("Enter string :");
str=br.readLine();
if(str.startsWith("A")||str.endsWith("OBJ"))
fos.write(str.getBytes());
}
fos.close();
System.out.println("Data is written in file:");
}
}
3. BufferedInputStream and BufferedOutputStream
-- BufferedInputStream and BufferedOutputStream
classes use an internal array of byte called as
Buffer,for the purpose of storing data while reading
and writing respectively.
--Buffered streams are considered as more efficient as
compared to similar non buffered streams.
import java.io.*;
public class BuffEx14
{
public static void main(String[]app)
{
File file=new File(“d1.txt");
FileInputStream fn=null;
BufferedInputStream bs=null;
try
{
fn=new FileInputStream(file);
bs=new BufferedInputStream(fn);
byte[]buffer=new byte[1024];
int br=0;
while((br=bs.read(buffer))!=-1)
{
System.out.println(new String(buffer,0,br));
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
import java.io.*;
public class BuffEx2
{
public static void main(String[]args)
{
File file=new File(“d3.txt");
FileOutputStream fs=null;
BufferedOutputStream bs=null;
try
{
fs=new FileOutputStream(file);
bs=new BufferedOutputStream(fs);
bs.write("Writing data in file" .getBytes());
bs.write("using BufferedOutputStream" .getBytes());
bs.flush();
System.out.println("Data written in file:");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
6.4 Chracter Stream Classes:Using Stream
A.CharArrayReader And CharArrayWriter
--The charArrayReader class is used to read chracter array as a reader (stream) while charArrayWriter
class is used to write output to a character array.
import java.io.*;
public class ChracterEx1
{
public static void main(String[]args)throws IOException
{
char[]arr={'p','h','o','e','n','i','x'};
CharArrayReader rd=new CharArrayReader(arr);
CharArrayWriter rw=new CharArrayWriter();
int i;
while((i=rd.read())!=-1)
{
char ch=(char)i;
System.out.println(ch);
rw.write(i);
}
System.out.println("\n"+rw);
}
}
import java.io.*;
public class ChracterEx2
{
public static void main(String[]args)throws IOException
{
char[]arr={'P‘,'h',' ‘,'e',' ','i',' '};
CharArrayReader rd=new CharArrayReader(arr);
CharArrayWriter rw=new CharArrayWriter();
int i;
int cnt=0;
while((i=rd.read())!=-1)
{
char ch=(char)i;
rw.write(i);

if(ch==' ')
cnt++;
}
System.out.println("\n"+rw);
System.out.println("Number of white spaces are:"+cnt);
}
}
B.BufferedReader And BufferedrWriter
--BufferedReader And BufferedrWriter use an internal buffer for the purpose of storing data
while readind and writing respectively.
--A method readLine() is provided by BufferedReader,which reads line and returns a string.

import java.io.*;
public class BuffReaderEx1
{
public static void main(String[]args)throws IOException
{
File file=new File("Myfile.txt");
FileWriter fw=null;
BufferedWriter bw=null;
try
{
fw=new FileWriter(file);
bw=new BufferedWriter(fw);
bw.write("writing and reading data \n");
bw.write("Using BufferedWrite and \n");
bw.write("BufferedReader.");
bw.flush();
}
catch(IOException e)
{
e.printStackTrace();
}
FileReader fr=null;
BufferedReader br=null;
try
{
fr=new FileReader(file);
br=new BufferedReader(fr);
String str=null;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
C.FileReader and FileWriter
--Java File Writer and FileReader classes are used to read and write data from
text files.
--Constructor of FileWriter
i)FileWriter(File file):
Constructor a FIleWriter object,given a file object.
ii)FileWriter(File file,boolean append)
Constructs a FileWriter object,given a file object.
III)FileWriter(FileDescriptor fd):
Constructs a FileWriter object associated with a file descriptor.
IV)File Writer(String fileName):
--Constructs a FileWriter object,given a file name.
V)FileWriter(String fileName,Boolean append):
--Construts a FIleWriter object,given a file name with a Boolean indicating
whether or not to append the data written.
--Constructor of FileReader
i)FileReader(File file):
Creates a FileReader,given the file to read from.
ii)FileReader(FileDescriptor fd):
Creates a new FileReader,given the FileDescriptor to read from.
IV)File Writer(String fileName):
--Creates a new FileReader,given the name of the file to read from.
Methods of FileReader
int read() It is used to return a chracter in ASCII form.It returns -1
at the end of file.
void close() It is used to close the FileReader class.
6.5.Using the file class
--Instance of this class represents the name of a file or directory on the host file
system.
--A file is specified by a pathname,which can either be an absolute pathname or a
pathname relative to the current working directory.
--The pathname must follow the naming conventions of the host platform.
--The file class is intended to provide an abstraction that deals with most of the
machine dependent complexities of files and pathnames in a machine
independent fashion.
6.5.1 Constructors of file class
1.File(File dir,String name)
--Creates a file instance that represents the file with the specified name in the
specified directory.
2.File(String Path)
--Creates a file instance that represents the file pathname of which is the given path
argument.
3.File(String Path,String name)
--Creates a file instance pathname of which is the pathname of the specified directory
followed by the separator chracter followed by the name-argument.
Method Description
Boolean canWrite() Returns true if the file is writable.
Boolean canRead() Returns true if the file is readable.
Boolean isHidden Returns true if the file is hidden.
Boolean isAbsolute() Returns true if the abstract pathname is absolute.
Boolean isDirectory() Returns true if the denoted by abstract pathname is a
directory.
Boolean isFile() Returns true if the file denoted by abstract pathname is a
normal file.
String getName() It returns the name of the file or directory.
String getParent() It returns an array containing list of file names of associted
directory.
File[]listFiles() It returns an array containing list of file names of associated
directory
Boolean mkdir() It creates the directory named by this abstract pathname.
getPath() Returns name of the file along with parent directory.
long lastModified() Returns last modified date time details.
Boolean delete Deletes the file or directory.
• import java.io.*;
• class FileTest3
• {
• public static void main(String args[])
• {
• File f=new File(".txt");
• System.out.println("Writable:"+f.canWrite());
• System.out.println("Readable:"+f.canRead());
• System.out.println("Hidden:"+f.isHidden());
• System.out.println("Absolute:"+f.isAbsolute());
• System.out.println("Directory:"+f.isDirectory());
• System.out.println("File:"+f.isFile());
• System.out.println("Name:"+f.getName());
• System.out.println("Parent:"+f.getParent());
• System.out.println("Writable:"+f.canWrite());
• System.out.println("Path:"+f.getPath());
• System.out.println("Last Modified:"+f.lastModified());
• System.out.println("Length:"+f.length());
• }
• }
• import java.io.*;
• class FileTest4
• {
• public static void main(String args[])throws IOException
• {
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

• System.out.println("Enter Directory name:");

• String directory=br.readLine();
• File file=new File(directory);
• if(file.isDirectory())
• {
• String list[]=file.list();
• System.out.println("List of files:");
• for(String nm:list)
• {
• File ele=new File(directory,nm);
• if(ele.isFile())
• System.out.println(ele);
• }
• System.out.println("\n\nList of Directories:");
• for(String nm:list)
• {
• File ele=new File(directory,nm);
• if(ele.isDirectory())
• System.out.println(ele);
• }
• }
• else

• System.out.println("Directory does not exist");

• }
• }
• import java.io.*;
• public class FileTest1
• {
• public static void main(String[]args)throws IOException
• {
• String file="r1.txt";
• FileInputStream fin=new FileInputStream(file);
• DataInputStream din=new DataInputStream(fin);
• byte b[]=new byte[0];
• din.read(b);
• String str;
• while((str=din.readLine())!=null)
• {
• String str1=str.toUpperCase();
• System.out.println(str1);
• }
• fin.close();
• din.close();
• }
• }

You might also like