Java I/P Presentation

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 44

Java IO

Nguyễn Văn Khiết


Content
• Introduction
• Working with byte-oriented stream
• Working with character-oriented stream
Introduction
• java.io package provides classes,
interfaces for I/O processing in java.
• Java I/O is separated into 2 groups:
– Binary I/O processing: using classes inherit
from java.io.InputStream and
java.io.OutputStream.
– Characters and text I/O processing: using
classes inherit from java.io.Reader and
java.io.Writer.
Stream
• Stream is one continuous group of
information from beginning to end
• Input streams are streams that move data
from outside world to your program.
• Output Stream are streams that write data
from your java program to outside world.
Using byte-oriented streams
• Byte-oriented streams consist of : low level
byte stream and high level byte stream.
• Low level byte streams read/write data
directly from sources.
• High level byte streams use low level byte
streams inside and provide more
complicated operations on data
– Use low level streams to read data
– Provide operation on data
Using byte-oriented streams
• Low level Byte stream:
– java.io.InputStream an java.io.OutputStream
are abstract class.
java.io.InputStream
• java.io.InputStream methods:
– int available( )
– void close( )
– void mark(int numBytes)
– boolean markSupported( )
– int read( )
– int read(byte buffer[ ])
– int read(byte buffer[ ], int offset, int numBytes)
– void reset( )
– long skip(long numBytes)
java.io.InputStream
• Some subclasses of InputStream:
– FileInputStream
– FilterInputStream
– ByteArrayInputStream
– StringBufferInputStream
– SequenceInputStream
– PipedInputStream
–…
java.io.OutputStream
• java.io.OutputStream methods:
– void close( )
– void flush( )
– void write(int b)
– void write(byte buffer[ ])
– void write(byte buffer[ ], int offset,int
numBytes)
java.io.OutputStream
• Some subclasses of OutputStream:
– FileOutputStream
– FilterOutputStream
– ByteArrayOutputStream
– PipedOutputStream
–…
Predefine objects in Java I/O
• System.in
• System.out
• System.err
System.in
• An InputStream read data directly from
keyboard.
System.out
• Write data to console
• An instance of PrintStream
– Inherits OutputStream
– Provides print() and println() methods
– From J2SE 1.5, PrintStream was added 2
new methods: format() and printf()
System.err
• Write error to console
Redirect System.in, System.out,
System.err
• public static void setIn(InputStream in)
• public static void setOut(PrintStream out)
• public static void setErr(PrintStream err)
Working with file streams
• Reading binary data from file with a
FileInputStream
• Writing binary data to file with a
FileOutputStream
Reading data from file
• Create an instance of FileInputStream,
initiating with a filename
• Uses read() methods to read data
• Call close() to close stream.
Writing data to file
• Create an instance of FileOutputStream,
initiating with a filename.
• Uses write() mthodes to write data to file
• Call flush() to push all data still in buffer
(not actually write to file) to file.
• Call close() to close stream
Some other InputStreams
• ByteArrayInputStream
• ObjectInputStream
• PipedInputStream
• SequenceInputStream
• StringBufferInputStream
Some other OutputStreams
• ByteArrayOutputStream
• ObjectOutputStream
• PipedOutputStream
Working with high level
byte-oriented streams
• High level byte streams transform the data
along the way or providing additional
functionality.
• High level byte streams
– Have an inside stream. Use this stream to read
data.
– Transform data or provide additional
functionality
• Constructors of high level byte stream
require another stream.
• High level input stream inherit from
FilterInputStream
• High level output stream inherit from
FilterOutputStream
Read and write primitive data
types with byte streams
• There a need to read and write primitive
data types using byte streams.
• DataInputStream and DataOutputStream
are high level stream that provide this
functionality.
• DataInputStream implement DataInput interface
– boolean readBoolean( )
– byte readByte( )
– char readChar( )
– double readDouble( )
– float readFloat( )
– int readInt( )
– long readLong( )
– short readShort( )
– int readUnsignedByte()
– int readUnsignedShort()
– String readUTF()
• DataOutputStream implement DataOutput
interface
– void writeBoolean(boolean val )
– void writeByte(int val )
– void writeChar(int val )
– void writeDouble(double val )
– void writeFloat(float val )
– void writeInt(int val )
– void writeLong(long val )
– void writeShort(int val )
– void writeUTF(String s)
BufferedInputStream and
BufferedOutputStream
• These class provide buffering for input and
output operations. Use these class to
increase efficiency.
• System.in is a BufferedinputStreamObject.
BufferedInputStream and
BufferedOutputStream
• BufferedInputStream
– BufferedInputStream constructors:
• public BufferedInputStream(InputStream in)
• public BufferedInputStream(InputStream in, int
size)
• BufferedOutputStream
– BufferedOutputStream(OutputStream out)
– BufferedOutputStream(OutputStream out, int
size) :
BufferedInputStream and
BufferedOutputStream
• BufferedInputStream
– Override methods defined in InputStream
– Has an internal buffer array. As bytes from the
stream are read or skipped, the internal buffer
is refilled as necessary from the contained
input stream, many bytes at a time.
– The way of using buffer totally transparent to
developers.
PrintStream
• PrintStream implements methods for
displaying data types textually.
• print(), println() are methods of PrintStream
• Construct a PrintStream object:
PrintStream ps=new PrintStream(OutputStream
out);
PrintStream ps=new PrintStream(OutputStream
out, boolean autoflush);
RandomAccessFile
• RandomAccessFile is not a stream, it
doesn’t inherit from InputStream,
OutputStream
• RandomAccessFile implements DataInput
and DataOutput interfaces.
• Provides methods for reading, writing
primitive datatypes and locating file pointer
• RandomAccessFile methods:
– void seek(long newPos)
– boolean readBoolean( )
– byte readByte( )
– char readChar( )
– double readDouble( )
– float readFloat( )
– int readInt( )
– long readLong( )
– short readShort( )
– void writeBoolean(boolean val )
– void writeByte(int val )
– void writeChar(int val )
– void writeDouble(double val )
– void writeFloat(float val )
– void writeInt(int val )
– void writeLong(long val )
– void writeShort(int val )
Using character-oriented stream
• Character-oriented streams are used to
read and write data in characters, text
format.
• Character-oriented stream read and write
text in Unicode
• Character-oriented streams consist of
readers and writers.
– Character-oriented input stream (readers)
inherit from java.io.Reader
– Character-oriented output stream (writers)
inherit from java.io.Writer
Reader
• Reader is an abstract class
– abstract void close( )
– void mark(int numChars)
– boolean markSupported( )
– int read( )
– int read(char buffer[ ])
– abstract int read(char buffer[ ], int offset, int
numChars)
– int read(CharBuffer buffer)
– boolean ready( )
– void reset( )
– long skip(long numChars)
Reader
• CharArrayReader
• FilterReader
• InputStreamReader
• PipedReader
• StringReader
• FileReader
• …
Writer
• Writer is an abstract class
• Writer methods:
– Writer append(char ch)
– Writer append(CharSequence chars)
– Writer append(CharSequence chars, int begin, int end)
– abstract void close( )
– abstract void flush( )
– void write(int ch)
– void write(char buffer[ ])
– abstract void write(char buffer[ ], int offset, int numChars)
– void write(String str)
– void write(String str, int offset, int numChars)
Writer
• CharArrayWriter
• OutputStreamWriter
• PipedWriter
• StringWriter
• PrintWriter
• FileWriter
• …
FileWriter
• Used for writing text data to file, construct
with a filename.
FileReader
• Used for reading unicode text files.
• Construct with a filename.
• A FileNotFoundException may be thrown if
the file does not exist.
PrintWriter
• Prints formatted representations of objects
to a text-output stream
• Construct a PrintWriter object
– PrintWriter(Writer out)
– PrintWriter(Writer out, boolean autoFlush)
– PrintWriter(String fileName)
– PrintWriter(String fileName, String csn)
– PrintWriter(File file)
– PrintWriter(File file, String csn)
– PrintWriter(OutputStream out)
– PrintWriter(OutputStream out, boolean autoFlush)
PrintStream vs PrintWriter
• PrintStream is used to write data in bytes
and PrintWriter is used where it is required
to write data in characters
• PrintStream is a byte stream (subclass of
OutputStream) and PrintWriter is a
character stream (subclass of Writer)
BufferedReader
• BufferedReader is a high level read, read
data from another reader.
• BufferedReader provides the followings
methods:
– int read( )
– int read(char data[])
– int read(char data[], int start, int max)
– String readLine()
InputStreamReader và
OutputStreamWriter
• InputStreamReader implements a
character input stream that read bytes
from a byte-oriented input stream and
converts the bytes to characters.
• InputStreamReader is suitable for reading
character data from sources provide data
in bytes only (like System.in)
Exercise 1
• Write a student management program with
the following requirements
– Add student. (Student information: student id,
student name, grade point average (GPA),
image, address, notes)
– Update student information
– Delete a student
– View student list
• With the student id in ascending order
• With the GPA in ascending order
– Save student list into file(s).
– Import/Export student list to/from text file (csv)
Exercise 1
• Deadline: 23:50 27/10/2019

You might also like