I/O in java
Java IO Classes
• Java I/O is based on a class hierarchy.
• Base classes are used to describe the basic functionality required.
• Derived classes provided the functionality for specific kinds of I/O environments.
2
I/O Stream
Stream A stream is an abstraction that either
produces or consumes information.
Input Streamreads or consumes information
Input Stream Sourcekeyboard or file
Output Stream writes or produces information
Output Stream DestinationsMonitor or file
Some Abstract Base Classes
•
InputStream
– for reading a stream of bytes
•
OutputStream
– for writing a stream of bytes
•
Reader
– reading a stream of characters
•
Writer
– writing a stream of characters.
Nihar Ranjan Roy 4
Byte Oriented
Class
OutputStream
• All
byte
stream writers
are based on the class
OutputStream
(they extend
OutputStream
)
• Some of the methods:
– void write(int b) throws IOException – void write(byte[] b) throws IOException – void flush() throws IOException
– void close() throws IOException
throws IOException
• Everything here can throw an
IOException• If you use any of these methods, you must
catch
IOException(or
Exception).
IOException
6
Class
Reader
• All
character
stream
readers are based on
the class
Reader(they extend
Reader)
• Some of the methods:
– int read()
– int read(char[] cbuf) – boolean ready()
– void close()
Class
Writer
• All character stream writers are based on the
class Writer (they extend Writer)
• Some of the methods:
– void write(int c)
– void write(char[] cbuf) – void write(String str) – void flush()
– void close()
Abstract Classes
• You can't create an InputStream object!
– or OutputStream or Reader or Writer
• You create some object of a derived class
– a specific kind of InputStream object, perhaps a FileInputStream
– but your code can be written to work with any kind of
InputStream
System.out
• System.out is actually a kind of OutputStream:
– it's a PrintStream object, but you don't need to know that to
use it as an OutputStream
OutputStream stdout = System.out; stdout.write(104); // ASCII 'h'
stdout.flush();
IOExceptions!
public static void main(String[] args) { OutputStream stdout = System.out;
try {
stdout.write(104); // 'h' stdout.write(105); // 'i' stdout.write(10); // '\n'
} catch (IOException e) { e.printStackTrace(); }
}
Another way…
public static void main(String[] args)
throws IOException {
OutputStream stdout = System.out; stdout.write(104); // 'h'
stdout.write(105); // 'i' stdout.write(10); // '\n' }
System.in
System.in
is a type of
InputStreambyte[] b = new byte[10];
InputStream stdin = System.in; stdin.read(b);
Character Streams
• Remember that Java supports UNICODE!
– support for non-ASCII characters.
• Java also supports ASCII (obviously).
• BUT – since characters are not necessarily a single byte – we need more than byte streams.
InputStreamReader
• An InputStreamReader is a bridge from byte streams to
character streams.
– You need to have an InputStream to feed the InputStreamReader.
• Each call to InputStreamReader.read() returns one char,
but may read multiple bytes from the InputStream.
InputStreamReader
attached to
stdin
InputStreamReader isr = new
InputStreamReader( System.in );
char c;
c = (char) isr.read(); System.out.write( c);
BufferedReader
• A type of
Readerthat does internal buffering.
– more efficient.
• Provides everything from
Reader, plus:
String readLine()
– reads up to '\n’– String returned does not include the line termination char(s).
Attaching a
BufferedReader
to stdin
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(isr);
String foo = bf.readLine();
Character Stream Output
• OutputStreamWriter: a bridge (converts from characters
to byte stream).
• BufferedWriter: efficient Writer.
BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter ( System.out ) );
File Handling
Create a file object
package required is Import java.io.*;
File inFile=new File(“C:\\abc.dat”);
Or
File inFile=new File(“c:\\myfolder”,”abc.txt”);
boolean exists() Tests whether the file or directory denoted by this abstract pathname exists.
void deleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
boolean canExecute() Tests whether the application can execute the file denoted by this abstract pathname.
boolean canRead() Tests whether the application can read the file denoted by this abstract pathname.
boolean canWrite() Tests whether the application can modify the file denoted by this abstract pathname.
boolean delete() Deletes the file or directory denoted by this abstract pathname.
String getName() Returns the name of the file or directory denoted by this abstract pathname.
String getParent() Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory.
booleanisFile() Tests whether the file denoted by this abstract pathname is a normal file.
booleanisHidden() Tests whether the file named by this abstract pathname is a hidden file.
longlastModified() Returns the time that the file denoted by this abstract pathname was last modified.
longlength() Returns the length of the file denoted by this abstract pathname.
boolean mkdir() Creates the directory named by this abstract pathname.
String[] list() Returns an array of strings naming the files and
directories in the directory denoted by this abstract pathname.
Problem
Write a program in java that
prints all the files in a
specified directory
Listing all files from a directory
File mydir=new File(“c:\\javaprgs”);
String fileList[] = mydir.list();
for(int i=0; i<fileList.length; i++)
System.out.println( fileList[i] );
Nihar Ranjan Roy 25
FileInputStream
• Class FileInputStream
• java.lang.Object
– java.io.InputStream
• java.io.FileInputStream
FileInputStream is meant for reading streams
of raw bytes such as image data
FileInputStream
(
File
file)
FileInputStream
(
String
name)
Few Methods
Nihar Ranjan Roy 27
int read()
Reads a byte of data from this input stream.
int read(byte[] b) Reads up to b.length bytes of data from this input stream into an array of bytes.
int read(byte[] b, int off, int len) Reads up to len bytes of data from this input stream into an array of bytes.
Problem
Write a program in java in
which the program prints its
source code.
import java.io.*;
class ReadFromFile {
public static void main(String args[])
throws IOException { int ch;
FileInputStream fo=new
FileInputStream("c:\\myJava\\ReadFromFile.java"); while((ch=fo.read())!=-1)
{ System.out.print((char)ch); }
fo.close(); }
}
Writing to a file
• Class is FileOutPutStream
• FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.
Nihar Ranjan Roy 30
Constructor Summary
FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(String name)
Creates an output file stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Some Methods
Nihar Ranjan Roy 31
void write(byte[] b)
Writes b.length bytes from the specified byte array to this file output stream.
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this file output stream.
void write(int b)
Writes the specified byte to this file output stream.
void close()
Problem
Write a program in java to copy a
file
myCopy sourceFile DestationFile
Class FileReader
• java.lang.Object
– java.io.Reader
• java.io.InputStreamReader
– java.io.FileReader
FileReader is meant for reading streams of
characters. For reading streams of raw bytes, consider using a FileInputStream.
Constructor Summary
FileReader ( File file)
FileReader ( String fileName)
Print the Source Code using FileReader
import java.io.*;
class FileReaderTest
{public static void main(String args[]) throws Exception {
FileReader fr=new FileReader("FileReaderTest.java"); BufferedReader br=new BufferedReader(fr);
String str=null;
while((str=br.readLine())!=null) {System.out.println(str); }
} }
Class FileWriter
java.lang.Object java.io.Writer
java.io.OutputStreamWriter
java.io.FileWriter
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
Constructor Summary
FileWriter(File file)
FileWriter(File file, boolean append)
FileWriter(String fileName)
FileWriter(String fileName, boolean append)
Problem
Write a program in java that asks the use to enter something about him. What ever the user enters it should be stored in to a file.
Nihar Ranjan Roy 37
import java.io.*;
class FileWriterTest
{public static void main(String args[]) throws Exception {
FileWriter fw=new FileWriter("FileWriter.dat"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int ch;
System.out.println("Please enter something about u"); while((ch=br.read())!=-1)
{ fw.write(ch);
}
fw.close();
System.out.println("Done Successfully"); }
DataOutputStream
DataOutputStream object
defines the methods used to write primitive data types
to output streams
Constructor Summary
DataOutputStream( OutputStream out)
Creates a new data output stream to write data to the specified underlying output stream.
Nihar Ranjan Roy 39
void writeBoolean(boolean v) void writeByte(int v)
void writeBytes( String s) void writeChar(int v)
void writeChars( String s) void writeDouble(double v) void writeFloat(float v)
void writeInt(int v)
Writing Primitives Data types to file
import java.io.*;
class PrimitiveWrite
{public static void main(String args[]) throws IOException {
DataOutputStream dos=
new DataOutputStream(
new FileOutputStream("Primitive.dat")); dos.writeInt(23);
dos.writeBoolean(true); dos.close();
} }
DataInputStream
A DataInputStream lets an application read primitive Java data types from an underlying input stream in a machine-independent way
Constructor Summary
DataInputStream ( InputStream in)
Creates a DataInputStream that uses the specified underlying InputStream.
Nihar Ranjan Roy 42
boolean readBoolean() byte readByte()
char readChar() double readDouble() float readFloat() int readInt() long readLong() short readShort()
Use of DataInputStream
Nihar Ranjan Roy 43
import java.io.*;
class PrimitiveRead {
public static void main(String args[]) throws IOException {
DataInputStream dis=
new DataInputStream(
new FileInputStream("Primitive.dat")); System.out.println(dis.readInt());
System.out.println(dis.readBoolean()); dis.close();
Problem
Write a program in java that accepts students details NameString
Rollint
stores them to a file “student.dat”
Writing objects to file
Nihar Ranjan Roy 45
class Student implements Serializable {
String name; int roll;
Writing objects to file
Nihar Ranjan Roy 46
import java.io.*; class writeObject {
public static void main(String args[]) throws Exception {Student st=new Student("Nihar",143);
ObjectOutputStream oos=
new ObjectOutputStream(
new FileOutputStream("Object.dat"));
oos.writeObject(st);
System.out.println("Written Successfully"); oos.close();
Reading objects from file
Nihar Ranjan Roy 47
import java.io.*; class readObject {
public static void main(String args[]) throws Exception {
ObjectInputStream ois=
new ObjectInputStream(
RandomAccessFile
• RandomAccessFile in java enables us to read and
write bytes, text and java data types to any location in a file.
• The term random means data can be written or read from random location within a file.
• This class also provides permissions like read and
write and allows files to be accessed in read only and read write mode.
• Two ways to create the file
RandomAccessFile(File name,String mode) or
RandomAccessFile(String pathname,String mode)
Modes
”r” read only
”rw” read and write.
We can read or write the primitive data types through readXXX() and writeXXX() methods
Nihar Ranjan Roy 50
class randomAccessFile {
Sequence InputStream
A SequenceInputStream represents the logical concatenation of multiple input streams.
It starts out with an ordered collection of input
streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the
contained input streams.
SequenceInputStream( InputStream s1, InputStream s2)
Problem
Write a program in java that takes two file names as command prompts and reads the files in the same order once the first file is finished it starts reading the second one.
Nihar Ranjan Roy 52
HINT
FileInputStream f1=new FileInputStream(args[0]) FileInputStream f2=new FileInputStream(args[1])
SequenceInputStream sis=new SequenceInputStream(f1,f2);