I/O
Basics
-------------
Java
programs perform I/O through streams.
Two
types of streams:
1. Byte Streams
2. Character Streams
The
Byte Stream Classes
----------------------------
InputStream
OutputStream
The
Character Stream Classes
----------------------------------
Reader
Writer
Reading
Console Input
--------------------------
System.in
refers to an object of type InputStream, it can be used for inputStream.
Creates
a BufferedReader that is connected to the keyboard.
syntax:
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Reading
Characters
--------------------------
To
read a character from a BufferedReader, use read().
syntax:
int read() throws IOException
It returns -1 when the end of the
stream is encountered.
//Use a BufferedReader to read
characters from the console.
import java.io.*;
class BRRead{
public static void
main(String args[])throws IOException
{
char c;
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter
a characters, 'q' to quit.");
do
{
c=(char)br.read();
System.out.println(c);
}while(c!='q');
}
}
Reading
Strings
================
syntax:
String
readLine()throws IOException
//Reading
a string from console using BufferedReader
import
java.io.*;
class
BRReadLines{
public static void main(String
args[])throws IOException
{
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter
Lines of text.\nEnter 'stop' to quit.");
do
{
str=br.readLine();
System.out.println(str);
}while(!str.equals("stop"));
}
}
Writing
Console Output
-----------------------------
syntax:
void write(int byteval) throws
IOException
import
java.io.*;
class
WriteDemo{
public static void main(String
args[])throws IOException
{
int b;
b='A';
System.out.write(b);
System.out.write('\n');
}
}
The
PrintWriter Class
----------------------------
syntax:
PrintWriter(OutputStream
outputstream,boolean flushOnNewline)
PrintWriter
that is connected to console output:
PrintWriter pw=new
PrintWriter(System.out,true);
import
java.io.*;
public
class PrintWriterDemo{
public static void main(String
args[])throws IOException{
PrintWriter pw=new
PrintWriter(System.out,true);
pw.println("This is a
string");
int i=-7;
pw.println(i);
double d=4.5e-7;
pw.println(d);
}
}
File
------
Managing
Input /Output Files in Java
=====================================
A
file is a collection of related records placed in a particular area on the
disk.
Storing
and managing data using files is known as file processing which includes tasks
such as creating files, updating files and manipulation of data.
Java
also provides capabilities to read and write class objects directly. The process of reading and writing objects is
called object serialization.
Stream
Classes
==============
The
java.io package contains a large number of stream classes that provide
capabilities for processing all types of data.
1.
Byte stream classes that provide support for handling I/O operation on bytes.
2. Character stream classes that provide support
for manaing I/O operations on characters.
Byte
Stream Classes
===================
Java
provides two kinds of byte stream classes:
input stream classes and output stream
classes.
Input
Stream Classes:
=====================
Input
stream clases that are used to read 8-bit bytes include a super class known as
InputStream and a number of subclasses for supporting various input-related
functions.
The
InputStream class defines methods for performing input functions such as
Closing
streams
Marking
positions in streams
Skipping
ahead in a stream
Finding
the number of bytes in a stream
Summary
of InputStream Methods
----------------------------
Method Description
read() Reads a byte from
the input stream
read(byte
b[]) Reads an array of
bytes into b
read(byte
b[],int n,int m) Reads m bytes into b starting from nth
byte.
available() Gives number of bytes
available in the input
skip(n) Skips over
n bytes from the input stream
reset() Goes back
to the beginning of the stream
close() Closes the
input stream
The
DataInput interface contains the following methods:
readShort()
readInt()
readLong()
readFloat()
readDouble()
readLine()
readChar()
readBollean()
readUTF()
The
OutputStream includes methods that are designed to perform the followig tasks:
Writing
bytes
Closing
stream
Summary
of OutputStream Methods
Method Description
write() Writes
a byte to the output stream
write(byte[]
b) Writes all
bytes in the array b to the
output
stream
write(byte[]
b,int n,int m) Writes m bytes from
array b starting
from
nth byte
close() Closes
the output stream
flush() Flushes
the output stream
The
following methods contained in DataOutput interface
writeShort()
writeInt()
writeLong()
writeFloat()
writeDouble()
writeBytes()
writeChar()
writeBoolean()
writeUTF()
=======================================================
Using
the File Class
=====================
The
java.io package includes a class known as the File class that provides support
for creating files and directories. The
class includes several constructors for instantiating the File objects.
This
class also contains several methods for supporting the operation such as
Creating
a file
Opening
a file
Closing
a file
Deleting
a file
Getting
the name of a file
Getting
the size of a file
Checking
the existence of a file
Renaming
a file
Checking
whether the file is writable
Checking
whether the file is radable
//example
for file methods
import
java.io.File;
class
f1
{
static void show(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
File f1=new
File("s://selvarani/java/Files/f1.txt");
show("File
Name:"+f1.getName());
show("Path="+f1.getPath());
show("Absolute
path="+f1.getAbsolutePath());
show("Parent:"+f1.getParent());
show(f1.exists()?"Exists":"Does
not Exists");
show(f1.canWrite()?"It
Writable":"Is not writable");
show(f1.canRead()?"Is
Readable":"Is not Readable");
show(f1.isDirectory()?"is
Directory":"Is not Directory");
show(f1.isFile()?"Is
File":"IS not a file");
show(f1.isAbsolute()?"Is
absolute":"Is not absolute");
show("Last modified
"+f1.lastModified());
show("File
size"+f1.length()+"Bytes");
show(f1.isHidden()?"Hidden":"Not
Hidden");
}
}
Using
FilenameFilter
list()
method
--------------
To
include only those files that match a certain filename pattern, or filter.
String[]list(FilenameFilter
FFObj)
In
this form, FFObj is an object of a class that implements the FilenameFilter
interface. FilenameFilter defines only a
single method, accept(), which is called once for each file in a list.
syntax:
boolean accept(File directory, String
filename)
The accept() method returns true for
files in the directory specified by directory that should be included in the
list(that is, those that match the filename argument), and returns false for
those files that should be excluded.
//Display
the contents of given directory
import
java.io.File;
class
fdir
{
public static void main(String args[])
{
String
dirname="/selvarani";
File f1=new File(dirname);
if(f1.isDirectory())
{
System.out.println("Directory
of"+dirname);
String
s[]=f1.list();
for(int
i=0;i<s.length;i++)
{
File f=new
File(dirname+"/"+s[i]);
if(f.isDirectory())
System.out.println(s[i]+"
is a directory");
else
System.out.println(s[i]+"
is a file");
}
}
else
System.out.println(dirname+"
is not a directory");
}
}
//Display
the specific extends file
import
java.io.*;
class
onlyext implements FilenameFilter
{
String ext;
public onlyext(String ext)
{
this.ext="."+ext;
}
public
boolean accept(File dir,String name)
{
return name.endsWith(ext);
}
}
class
ext
{
public static void main(String args[])
{
String
dirname="/selvarani/java/Files";
File f1=new File(dirname);
FilenameFilter only=new
onlyext("java");
String s[]=f1.list(only);
for(int
i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
Input
/ Output Exceptions
==========================
Important
I/O Exception Classes and their Functions
I/O
Exception class Functions
EOFException Signals
that an end of the file or
end
of stream has been reached unexpectedly during input
FileNotFoundException Informs that a file could not
be
found
InterruptedIOException Warns that an I/O operations
has
been
interrupted
IOException Signals
that an I/O exception of
some
sort has occurred
=============
Creation
of Files
===============
Suitable
name for the file
Data
type to be stored
Purpose
(reading,writing, or updating)
Method
of creating the file
A
filename may contain two parts, a primary name and an optional period with
extension. Examples:
input.dat
test.doc
inventory
student.txt
rand.dat
Common
Stream Classes used for I/O operations
Characters
Read Write
Memory CharArrayReader CharArrayWriter
File FileReader FileWriter
Bytes
Read Write
Memory ByteArrayInputStream ByteArrayOutputStream
File FileInputStream FileOutputStream
The
use of direct approach.
------------------------------
FileInputStream
fis;//Declare a file stream object
try
{
//Assign the filename to the file
stream object
fis=new
FileInputStream("test.dat");
..........
}
catch(IOException
e)
.......
.......
//FileInputStream
fis=new FileInputStream("one.txt");
================
The
indirect approach uses a file object that has been initialized with the desired
filename.
...........
...........
File
inFile;//Declare a file object
inFile=new
File("test.dat");//assign the filename to the file
//object
FileInputStream
fis
try
{
//Give the value of the file object
//to the file stream object
fis=new FileInputStream(inFile);
...........
}
Byte
Input/Output
---------------------
=======================
FileInputStream
---------------
The
FileInputStream class creates an InputStream that you can use to read bytes
from a file.
constructors:
--------------
FileInputStream(String filepath)
FileInputStream(File fileobj)
ex:
FileInputStream
f1=new FileInputStream("demo.txt");
File
f2=new File("sample.txt");
FileInputStream
f3=new FileInputStream(f2);
//Display
a text file.
import
java.io.*;
class
ShowFile{
public static void main(String
args[])throws IOException
{
int i;
FileInputStream fin;
try
{
fin=new
FileInputStream(args[0]);
}
catch(FileNotFoundException
e)
{
System.out.println("File
Not found");
return;
}
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println("Usuage:ShowFile
File");
return;
}
do{
i=fin.read();
if(i!=-1)
System.out.print((char)i);
}while(i!=-1);
fin.close();;
}
}
FileOutputStream
--------------------
Constructor
--------------
FileOutputStream(String
filepath);
FileOutputStream(File
fileObject);
FileOutputStream(String
filepath,boolean append)
To
write to a file , we will use the write() method defined by FileOutputStream.
import
java.io.*;
public
class fileops
{
public static void main(String
args[])throws IOException
{
FileOutputStream fos=new
FileOutputStream("a.txt");
String s="God is
good";
byte b[]=s.getBytes();
for(int
i=0;i<b.length;i++)
fos.write(b[i]);
fos.close();
}
}
Copy
a text file
import
java.io.*;
class
CopyFile{
public static void main(String
args[])throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
//open input file
try
{
fin=new
FileInputStream(args[0]);
}
catch(FileNotFoundException
e)
{
System.out.println("Input
File Not found");
return;
}
//open output file
try
{
fout=new
FileOutputStream(args[1]);
}catch(FileNotFoundException
e)
{
System.out.println("Error
Opening OutputFile");
return;
}
//copy file
try
{
do{
i=fin.read();
if(i!=-1)
fout.write(i);
}while(i!=-1);
}catch(IOException e)
{
System.out.println("Error");
}
System.out.println("1
File copy");
fin.close();;
fout.close();
}
}
ex
for available()
import
java.io.*;
class
Filesize
{
public static void main(String argsp[])throws
Exception
{
int size;
FileInputStream fin=new
FileInputStream("one.java");
System.out.println("Available
bytes:"+(size=fin.available()));
fin.close();
}
}
Primitive
Data Types
If
we want to read/write the primitive datatypes such as integers and doubles, we
can use filter classes as wrappers on existing input and output streams to
filter data in the original stream. The
two filter classes used for creating "data streams" for handling
primitive types are DataInputStream and DataOutputStream.
A
data stream for input can be created as follows:
FileInputStream
fis=new FileInputStream(infile);
DataInputStream
dis=new DataInputStream(fis);
import java.io.*;
class primitive
{
public
static void main(String args[])throws IOException
{
File
primitive=new File("prim.dat");
FileOutputStream
fos=new FileOutputStream(primitive);
DataOutputStream
dos=new DataOutputStream(fos);
dos.writeUTF("Ramesh");
dos.writeInt(2000);
dos.writeDouble(12.23445);
dos.writeBoolean(true);
dos.writeChar('g');
dos.close();
fos.close();
FileInputStream
fis=new FileInputStream(primitive);
DataInputStream
dis=new DataInputStream(fis);
System.out.println(dis.readUTF());
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}
//Example for formats for write
import java.io.*;
class fdemo
{
public
static void main(String args[])throws IOException
{
String
source="Welcome to Csc";
byte
buf[]=source.getBytes();
FileOutputStream
of=new FileOutputStream("file.txt");
for(int
i=0;i<buf.length;i++)
{
of.write(buf[i]);
}
of.close();
FileOutputStream
f1=new FileOutputStream("file2.txt");
f1.write(buf);
f1.close();
FileOutputStream
f2=new FileOutputStream("file3.txt");
f2.write(buf,0,7);
f2.close();
}
}
ByteArrayInputStream
--------------------
Constructor
---------
ByteArrayInputStream(byte
array[]);
ByteArrayInputStream(byte
array[],int start,int number of bytes);
import
java.io.*;
class
baips
{
public static void main(String
args[])throws IOException
{
String
temp="abcdefghijklmnopqrstuvwxyz";
byte b[]=temp.getBytes();
ByteArrayInputStream in1=new
ByteArrayInputStream(b);
ByteArrayInputStream in2=new
ByteArrayInputStream(b,10,3);
int n=in1.available();
for(int i=0;i<n;i++)
{
int c=in1.read();
System.out.print((char)c);
}
n=in2.available();
System.out.print();
for(int i=0;i<n;i++)
{
int c=in2.read();
System.out.println((char)c);
}
}
}
-----------------------
reset()
import
java.io.*;
class
baipsreset{
public static void main(String
args[])throws IOException
{
String tmp="abc";
byte b[]=tmp.getBytes();
ByteArrayInputStream in=new
ByteArrayInputStream(b);
for(int i=0;i<2;i++)
{
int c;
while((c=in.read())!=-1)
{
if(i==0){
System.out.print((char)c);
}else
{
System.out.print(Character.toUpperCase((char)c));
}
}
System.out.println();
in.reset();
}
}
}
--------------------------
ByteArrayOutputStream
=====================
Constructor
===========
ByteArrayOutputStream();
ByteArrayOutputStream(int
number of bytes);
import
java.io.*;
class
baops
{
public static void main(String
args[])throws Exception
{
ByteArrayOutputStream f=new
ByteArrayOutputStream();
String s="Have a good
day";
byte buf[]=s.getBytes();
f.write(buf);
System.out.println(f.toString());
byte b[]=f.toByteArray();
for(int i=0;i<b.length;i++)
{
System.out.print((char)b[i]);
}
FileOutputStream
f2=new FileOutputStream("Test.txt");
f.writeTo(f2);
f2.close();
f.reset();
System.out.print("\n");
for(int i=0;i<3;i++)
{
f.write('*');
System.out.println(f.toString());
}
}
}
Concatenating
and Buffering Files
-----------------------------------
It
is possible to combine two or more input streams(files) into a single input
stream
(file). This process is known as concatenation of
files and is achieved using the
SequenceInputStream
class.
Java
also supports creation of buffers to store temporarily data that is read from
or written to a stream. The process is
known as buffered i/o operation.
Buffered
InputStream
=====================
Constructors:
-------------
BufferedInputStream(InputStream
object);
BufferedInputStream(InputStream
object,int buffered size);
Buffered
OutputStream
=====================
Constructors:
-----------
BufferedOutputStream(OutputStream
object);
BufferedOutputStream(OutputStream
object,int buffersize);
Sequence
Input Stream
=====================
Constructor
-----------
SequenceInputStream(InputStream
first,InputStream second);
The
SequenceInputStream class allows concatenate multiple InputStreams.
import
java.io.*;
class
seqbuffer
{
public static void main(String
args[])throws IOException
{
try
{
FileInputStream
f1=new FileInputStream("f1.txt");
FileInputStream
f2=new FileInputStream("b1.txt");
SequenceInputStream
f3=new SequenceInputStream(f1,f2);
FileOutputStream
f=new FileOutputStream("new.txt");
BufferedInputStream
in=new BufferedInputStream(f3);
BufferedOutputStream
out=new BufferedOutputStream(f);
int ch;
while((ch=in.read())!=-1)
{
out.write((char)ch);
System.out.print((char)ch);
}
in.close();
out.close();
f1.close();
f2.close();
}catch(Exception e)
{
System.out.println(e+"Error");
}
}
}
//Example
for ObjectInputStream and ObjectOutputStream
object
streams are created using the ObjectInputStream and ObjectOutputStream classes.
import
java.io.*;
class
employee implements Serializable
{
String name;
int no;
double sal;
employee(String s,int n,double d)
{
name=s;
no=n;
sal=d;
}
public String toString()
{
return "Name
"+name+" Number= "+no+" Salary ="+sal;
}
}
class
objdemo
{
public static void main(String
args[])throws Exception
{
employee e=new
employee(" Aruna ", 536 , 3000);
employee e1=new
employee(" Priya ", 596 , 7000);
employee e2=new
employee(" Raja ", 639 , 10000 );
FileOutputStream fos=new
FileOutputStream("temp.txt");
ObjectOutputStream oos=new
ObjectOutputStream(fos);
oos.writeObject(e);
oos.writeObject(e1);
oos.writeObject(e2);
oos.close();
fos.close();
FileInputStream fis=new
FileInputStream("temp.txt");
ObjectInputStream ois=new
ObjectInputStream(fis);
e=(employee)ois.readObject();
e1=(employee)ois.readObject();
e2=(employee)ois.readObject();
System.out.println(e);
System.out.println(e1);
System.out.println(e2);
ois.close();
fis.close();
}
}
Character
Stream
==================
FileReader:
----------
Constructor
----------
FileReader(String
Filepath)
FileReader(File
object)
import
java.io.*;
class
freader
{
public static void main(String
args[])throws IOException
{
try
{
FileReader f2=new
FileReader("one.txt");
int c;
while((c=f2.read())!=-1)
System.out.print((char)c);
f2.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FileWriter
===========
Constrctors:
FileWriter(String
filepath);
FileWriter(String
filepath,boolean append);
FileWriter(object);
import
java.io.*;
class
fwriter
{
public static void main(String
args[])throws IOException
{
try
{
FileWriter f1=new
FileWriter("abc.txt");
char
a[]={'h','a','i'};
for(int i=0;i<a.length;i++)
f1.write(a[i]);
f1.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
Buffered
Writer
---------------
Constructors:
BufferedWriter(Writer OutputStream);
BufferedWriter(Writer OutputStream,
int buffersize);
Buffered Reader:
---------------
Constructor:
BufferedReader(Reader InputStream);
BufferedReader(Reader InputStream, int
buffersize);
Random
Access Files
====================
As
stated earlier, the Random AccessFile class supported by the java.io package
allows us to create files can be used for reading and writing data with random
access.
We
can use one of the following two mode strings:
"r"
for reading only
"rw"
for both reading and writing
The
file pointer is moved using the method seek() in the RandomAccessFile class.
import
java.io.*;
class
random
{
public static void
main(String args[])throws IOException
{
RandomAccessFile r;
BufferedReader
in=new BufferedReader(new InputStreamReader(System.in));
String str;
r=new RandomAccessFile("name.txt","rw");
for(int
i=0;i<3;i++)
{
System.out.println("Enter
a string");
str=in.readLine();
r.seek(r.length());
r.writeChars(str+"\n");
}
r.seek(0);
while((str=r.readLine())!=null)
{
System.out.println(str);
}
r.close();
}
}
CharArrayReader:
Constructors:
CharArrayReader(char
array[]);
CharArrayReader(char
array[],int start,int number of characters);
CharArrayWriter:
constructors:
CharArrayWriter();
CharArrayWriter(int number of characters);
No comments:
Post a Comment