6.Managing InputOutput Files in Java
6.Managing InputOutput Files in Java
6.Managing InputOutput Files in Java
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
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";
}
}
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.
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));
• 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
• }
• }
• 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();
• }
• }