Vous êtes sur la page 1sur 42

IO Package

Uday Kumar
Streams
A stream is an abstraction that either produces or consumes
information.

Streams are unidirectional.

All streams behave in the same manner, even if the actual
physical devices to which they are linked differ.

Java implements streams within class hierarchies defined in
the java.io package.
Console
The Java.io.Console class provides methods to
access the character-based console device, if any,
associated with the current Java virtual machine.
void flush()
This method flushes the console and forces any buffered output to be written immediately.
Console format(String fmt, Object... args)
This method writes a formatted string to this console's output stream using the specified format string and
arguments.
Console printf(String format, Object... args)
This method is used to write a formatted string to this console's output stream using the specified format
string and arguments.
Reader reader()
This method retrieves the unique Reader object associated with this console.
String readLine()
This method reads a single line of text from the console.
String readLine(String fmt, Object... args)
This method provides a formatted prompt, then reads a single line of text from the console.
char[] readPassword()
This method reads a password or passphrase from the console with echoing disabled.
char[] readPassword(String fmt, Object... args)
This method provides a formatted prompt, then reads a password or passphrase from the console with
echoing disabled.
PrintWriter writer()
This method retrieves the unique PrintWriter object associated with this console.
Console Contd..
Byte Streams & Character Streams
Java 2 defines two types of streams: byte and character.

Byte streams provide a convenient means for handling input
and output of bytes.
Byte streams are used, when reading or writing binary data.

Character streams provide a convenient means for handling
input and output of characters.
They use Unicode and, therefore, can be internationalized.
Also, in some cases, character streams are more efficient than
byte streams.
1.Reader. A stream to read characters.
2.Writer. A stream to write characters.
3.InputStream. A stream to read binary data.
4.OutputStream. A stream to write binary data.
Streams
Byte Streams & Character Streams
Byte streams are defined by using two class hierarchies. At the
top are two abstract classes: InputStream and
OutputStream.
Two of the key methods are read( ) and write( ), which,
respectively, read and write bytes of data.
Both methods are declared as abstract inside InputStream
and OutputStream.

Character streams are defined by using two class hierarchies.
At the top are two abstract classes, Reader and Writer.

File (java.io.File)
File deals directly with files and the file system.

File class does not specify how information is retrieved from
or stored in files; it describes the properties of a file itself.

A File object is used to obtain or manipulate the information
associated with a disk file, such as the permissions, time,
date, and directory path, and to navigate subdirectory
hierarchies.

Instances of the File class are immutable; that is, once
created, the abstract pathname represented by a File object
will never change.

File
The following constructors can be used to create File objects:

File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
File file1 = new File ("C:\\temp\\myNote.txt"); // in Windows
File file2 = new File ("/tmp/myNote.txt"); // in Linux/Unix
public String getName()
Returns the name of the file or directory denoted by this abstract pathname.
public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
public String getPath()
Converts this abstract pathname into a pathname string.
public boolean isAbsolute()
Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise
public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
public boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract
pathname exists and can be read by the application; false otherwise.
public boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually
contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this
abstract pathname exists; false otherwise
public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname
exists and is a directory; false otherwise.
public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other
system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the
file denoted by this abstract pathname exists and is a normal file; false otherwise.
public long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified,
measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.

public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file
does not exist and was successfully created; false if the named file already exists.
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be
deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.
public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
public String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
public File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
public boolean mkdir()
Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise.
public boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory
was created, along with all necessary parent directories; false otherwise.
public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise.

public boolean setLastModified(long time)
Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise.
public boolean setReadOnly()
Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded;
false otherwise.
public static File createTempFile(String prefix, String suffix, File directory) throws IOException
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a
newly-created empty file.
public static File createTempFile(String prefix, String suffix) throws IOException
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to
invoking createTempFile(prefix, suffix, null). Returns abstract pathname denoting a newly-created empty file.
public int compareTo(File pathname)
Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
public int compareTo(Object o)
Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
public boolean equals(Object obj)
Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes
the same file or directory as this abstract pathname.
public String toString()
Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.
BYTE STREAMS
FileInputStream
The Java.io.FileInputStream class obtains input
bytes from a file in a file system.
This class is meant for reading streams of raw bytes such
as image data.
For reading streams of characters, use FileReader.

Constructors:
FileInputStream(File file)

FileInputStream(FileDescriptor fdObj)

FileInputStream(String name)
ByteArrayInputStream
The java.io.ByteArrayInputStream class contains an
internal buffer that contains bytes that may be read from
the stream. An internal counter keeps track of the next
byte to be supplied by the read method.
Closing a ByteArrayInputStream has no effect.
The methods in this class can be called after the stream has
been closed without generating an IOException.

Syntax:

ByteArrayInputStream(byte[] buf)

ByteArrayInputStream(byte[] buf, int offset, int length)
FilterInputStream
The Java.io.FilterInputStream class contains some other input
stream, which it uses as its basic source of data, possibly
transforming the data along the way or providing additional
functionality.

The class itself simply overrides all methods of InputStream with
versions that pass all requests to the contained input stream
The Subclasses of this class may further override some of these
methods and may also provide additional methods and fields.

Syntax:
protected FilterInputStream(InputStream in)
BufferedInputStream
For the byte-oriented streams, a buffered stream extends a
filtered stream class by attaching a memory buffer to the I/O
streams.

This buffer allows Java to do I/O operations on more than a
byte at a time, hence increasing performance. Because the
buffer is available, skipping, marking, and resetting of the
stream becomes possible.

public BufferedInputStream(InputStream in)
public BufferedInput Stream (Input Stream in, int bufferSize)
FileInputStream fis = new FileInputStream(aFile);
BufferedInputStream bis = new BufferedInputStream (fis);
Syntax:
Example:
DataInputStream
The Java.io.DataInputStream class lets an application read
primitive Java data types from an underlying input stream
in a machine-independent way.
An application uses a data output stream to write data that
can later be read by a data input stream.
DataInputStream is not necessarily safe for multithreaded
access.

Syntax:
DataInputStream(InputStream in)

Java.io.StringBufferInputStream class allows an
application to create an input stream in which the
bytes read are supplied by the contents of a
string.

Java.io.SequenceInputStream class represents
the logical concatenation of other input streams.

PushbackInputStream

Java.io.PushbackInputStream class adds
functionality to another input stream, namely
the ability to "push back" or "unread" one byte.

Syntax:
PushbackInputStream(InputStream in)
OUTPUT STREAMS
FileOutputStream
Java.io.FileOutputStream class is an output stream for
writing data to a File or to a FileDescriptor.
This class is meant for writing streams of raw bytes such
as image data.
For writing streams of characters, use FileWriter

Constructors:
FileOutputStream(File file)
FileOutputStream(File file, boolean append)
FileOutputStream(FileDescriptor fdObj)
FileOutputStream(String name)
FileOutputStream(String name, boolean append)
ByteArrayOutputStream
Java.io.ByteArrayOutputStream class implements an
output stream in which the data is written into a byte
array. The buffer automatically grows as data is
written to it.
Closing a ByteArrayOutputStream has no effect.
The methods in this class can be called after the stream
has been closed without generating an IOException.

Syntax:
ByteArrayOutputStream()
ByteArrayOutputStream(int size)
FilterOutputStream
Java.io.FilterOutputStream class is the
superclass of all classes that filter output
streams.
The class itself simply overrides all methods of
OutputStream with versions that pass all requests
to the contained output stream.
The Subclasses of this class may further override
some of these methods and may also provide
additional methods and fields.

FilterOutputStream Contd..
Java.io.BufferedOutputStream class implements a buffered output
stream. By setting up such an output stream, an application can
write bytes to the underlying output stream without necessarily
causing a call to the underlying system for each byte written.

Java.io.DataOutputStream class lets an application write primitive
Java data types to an output stream in a portable way. An
application can then use a data input stream to read the data back
in.

Java.io.PrintStream class adds functionality to another output
stream, the ability to print representations of various data values
conveniently.
CHARACTER STREAMS
Character Streams
Java.io.Reader class is a abstract class for
reading character streams.
protected Reader()
protected Reader(Object lock)

Java.io.Writer class is a abstract class for
writing to character streams.
protected Writer()
protected Writer(Object lock)
InputStreamReader
Java.io.InputStreamReader class is a bridge from
byte streams to character streams. It reads bytes
and decodes them into characters using a specified
charset
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, Charset cs)
InputStreamReader(InputStream in, CharsetDecoder dec)
InputStreamReader(InputStream in, String charsetName)
FileReader
Java.io.FileReader class is a convenience class for reading
character files.
The constructors of this class assume that the default character
encoding and the default byte-buffer size are appropriate.
FileReader is meant for reading streams of characters. For
reading streams of raw bytes, use FileInputStream.

Constructors:
FileReader(File file)
FileReader(FileDescriptor file)
FileReader(String fileName)
String Reader & String Writer
Java.io.StringReader class is a character stream
whose source is a string
StringReader()
StringReader(int initialSize)

Java.io.StringWriter class is a character stream
that collects its output in a string buffer, which
can then be used to construct a string.
StringWriter()
StringWriter(int initialSize)

BufferedReader
Java.io.BufferedReader class reads text from a character-
input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be
used.
Each read request made of a Reader causes a corresponding
read request to be made of the underlying character or byte
stream.

Constructors:

BufferedReader(Reader in)
BufferedReader(Reader in, int sz)
BufferedWriter
Java.io.BufferedWriter class writes text to a character-
output stream, buffering characters so as to provide for the
efficient writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size may be
used.
A Writer sends its output immediately to the underlying
character or byte stream.

Constructors:

BufferedWriter(Writer out)
BufferedWriter(Writer out, int sz)
CharArrayReader & Writer
Java.io.CharArrayReader class implements a
character buffer that can be used as a
character-input stream.

Java.io.CharArrayWriter class implements a
character buffer that can be used as an
Writer.The buffer automatically grows when
data is written to the stream.
Java Serialization
Java provides a mechanism, called object serialization where an
object can be represented as a sequence of bytes that includes
the object's data as well as information about the object's type
and the types of data stored in the object.

After a serialized object has been written into a file, it can be
read from the file and de-serialized that is, the type information
and bytes that represent the object and its data can be used to
recreate the object in memory.

Most impressive is that the entire process is JVM independent,
meaning an object can be serialized on one platform and de-
serialized on an entirely different platform.

Java Serialization Contd..
If a class to be serialized successfully, two conditions
must be met
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is
not serializable, it must be marked transient.
The keyword transient in Java used to indicate that the variable
should not be serialized.
ObjectInputStream
Java.io.ObjectInputStream class deserializes primitive data
and objects previously written using an
ObjectOutputStream.
It is used to recover those objects previously serialized. It
ensures that the types of all objects in the graph created from
the stream match the classes present in the Java Virtual
Machine.
Classes are loaded as required using the standard mechanisms.

Constructors:
protected ObjectInputStream()
ObjectInputStream(InputStream in)
ObjectOutputStream
Java.io.ObjectOutputStream class writes
primitive data types and graphs of Java objects to
an OutputStream.The objects can be read
(reconstituted) using an ObjectInputStream.

Constructors:
protected ObjectOutputStream()
ObjectOutputStream(OutputStream out)

Byte Stream vs Character Stream
Byte Stream Character Stream
1. OutputStream
2. InputStream
1. Writer
2. Reader
3. No Counterpart
4. No Counterpart
3. OutputStreamWriter
4. InputStreamReader
5. FileOutputStream
6. FileInputStream
5. FileWriter
6. FileReader
7. BufferedOutputStream
8. BufferedInputStream
7. BufferedWriter
8. BufferedReader
9. PrintStream 9. PrintWriter
10. DataOutputStream
11. DataInputStream

10. No counterpart
11. No counterpart
12. ObjectOutputStream
13. ObjectInputStream
12. No counterpart
13. No counterpart
I/O Classes
Types of I/O Stream Classes Type Description
File
File Reader
Character


Used to read from &
write to a file on file
system
FileWriter
FileInputStream
Byte
FileOutputStream
Memory
CharArrayReader
Character
CharArrayWriter
ByteArrayInputStream
Byte
ByteArrayoutputStream
Data COnversion
DataInputStream
Byte
DataoutputStream

Buffering
BufferedReader
Character
Buffer data while reading
& writing
Reduce no of access
require on
original datasource
More efficient
Used with other streams
BufferedWriter
BufferedInputStream
BufferedOutputStream
Converting between bytes & streams
InputStreamReader
Bridge b/w byte to
character stream
OutputStreamWriter
Byte

Vous aimerez peut-être aussi