+ All Categories
Home > Documents > IO Package

IO Package

Date post: 02-Jun-2018
Category:
Upload: shruthy236
View: 229 times
Download: 0 times
Share this document with a friend

of 42

Transcript
  • 8/11/2019 IO Package

    1/42

    IO Package

    Uday Kumar

  • 8/11/2019 IO Package

    2/42

  • 8/11/2019 IO Package

    3/42

    Console

    The Java.io.Consoleclass provides methods to

    access the character-based console device, if any,associated with the current Java virtual machine.

  • 8/11/2019 IO Package

    4/42

    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..

    http://www.tutorialspoint.com/java/io/console_flush.htmhttp://www.tutorialspoint.com/java/io/console_format.htmhttp://www.tutorialspoint.com/java/io/console_printf.htmhttp://www.tutorialspoint.com/java/io/console_reader.htmhttp://www.tutorialspoint.com/java/io/console_readline.htmhttp://www.tutorialspoint.com/java/io/console_readline_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_writer.htmhttp://www.tutorialspoint.com/java/io/console_writer.htmhttp://www.tutorialspoint.com/java/io/console_writer.htmhttp://www.tutorialspoint.com/java/io/console_writer.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readpassword.htmhttp://www.tutorialspoint.com/java/io/console_readpassword.htmhttp://www.tutorialspoint.com/java/io/console_readpassword.htmhttp://www.tutorialspoint.com/java/io/console_readline_formatted.htmhttp://www.tutorialspoint.com/java/io/console_readline.htmhttp://www.tutorialspoint.com/java/io/console_readline.htmhttp://www.tutorialspoint.com/java/io/console_readline.htmhttp://www.tutorialspoint.com/java/io/console_reader.htmhttp://www.tutorialspoint.com/java/io/console_printf.htmhttp://www.tutorialspoint.com/java/io/console_format.htmhttp://www.tutorialspoint.com/java/io/console_format.htmhttp://www.tutorialspoint.com/java/io/console_format.htmhttp://www.tutorialspoint.com/java/io/console_format.htmhttp://www.tutorialspoint.com/java/io/console_format.htmhttp://www.tutorialspoint.com/java/io/console_flush.htm
  • 8/11/2019 IO Package

    5/42

    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.

  • 8/11/2019 IO Package

    6/42

    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

  • 8/11/2019 IO Package

    7/42

    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 declaredas abstract inside InputStream

    and OutputStream.

    Character streams are defined by using two class hierarchies.

    At the top are two abstract classes, Reader and Writer.

  • 8/11/2019 IO Package

    8/42

  • 8/11/2019 IO Package

    9/42

    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.

  • 8/11/2019 IO Package

    10/42

    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

  • 8/11/2019 IO Package

    11/42

    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 abstractpathname 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.

  • 8/11/2019 IO Package

    12/42

    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 IOExceptionAtomically 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.

  • 8/11/2019 IO Package

    13/42

    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.

  • 8/11/2019 IO Package

    14/42

    BYTE STREAMS

  • 8/11/2019 IO Package

    15/42

    FileInputStream

    The Java.io.FileInputStreamclass obtains inputbytes 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)

  • 8/11/2019 IO Package

    16/42

    ByteArrayInputStream

    Thejava.io.ByteArrayInputStreamclass contains aninternal buffer that contains bytes that may be read fromthe stream. An internal counter keeps track of the nextbyte 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)

  • 8/11/2019 IO Package

    17/42

    FilterInputStream

    The Java.io.FilterInputStreamclass contains some other inputstream, which it uses as its basic source of data, possiblytransforming the data along the way or providing additionalfunctionality.

    The class itself simply overrides all methods of InputStreamwithversions that pass all requests to the contained input stream

    The Subclasses of this class may further override some of thesemethods and may also provide additional methods and fields.

    Syntax:

    protected FilterInputStream(InputStream in)

  • 8/11/2019 IO Package

    18/42

    BufferedInputStreamFor the byte-oriented streams, a buffered stream extends a

    filtered stream class by attaching a memory buffer to the I/Ostreams.

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

    pu lic

    BufferedInputStream(InputStream in)pu lic BufferedInput Stream (Input Stream in, int bufferSize)

    FileInputStream fis = new FileInputStream(aFile);

    BufferedInputStream bis = new BufferedInputStream (fis);

    Syntax:

    Example:

  • 8/11/2019 IO Package

    19/42

    DataInputStream

    The Java.io.DataInputStreamclass lets an application readprimitive Java data types from an underlying input streamin 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 multithreadedaccess.

    Syntax:

    DataInputStream(InputStream in)

  • 8/11/2019 IO Package

    20/42

    Java.io.StringBufferInputStreamclass allows an

    application to create an input stream in which the

    bytes read are supplied by the contents of a

    string.

    Java.io.SequenceInputStreamclass represents

    the logical concatenation of other input streams.

  • 8/11/2019 IO Package

    21/42

    PushbackInputStream

    Java.io.PushbackInputStreamclass adds

    functionality to another input stream, namely

    the ability to "push back" or "unread" one byte.

    Syntax:

    PushbackInputStream(InputStream in)

  • 8/11/2019 IO Package

    22/42

    OUTPUT STREAMS

  • 8/11/2019 IO Package

    23/42

    FileOutputStream

    Java.io.FileOutputStreamclass is an output stream forwriting data to a Fileor to a FileDescriptor.

    This class is meant for writing streams of raw bytes suchas 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)

  • 8/11/2019 IO Package

    24/42

    ByteArrayOutputStream

    Java.io.ByteArrayOutputStreamclass implements anoutput stream in which the data is written into a bytearray. The buffer automatically grows as data iswritten to it. Closing a ByteArrayOutputStream has no effect.

    The methods in this class can be called after the streamhas been closed without generating an IOException.

    Syntax:

    ByteArrayOutputStream()

    ByteArrayOutputStream(int size)

  • 8/11/2019 IO Package

    25/42

    FilterOutputStream

    Java.io.FilterOutputStreamclass is the

    superclass of all classes that filter output

    streams.

    The class itself simply overrides all methods of

    OutputStreamwith versions that pass all requests

    to the contained output stream.

    The Subclasses of this class may further overridesome of these methods and may also provide

    additional methods and fields.

  • 8/11/2019 IO Package

    26/42

    FilterOutputStream Contd..

    Java.io.BufferedOutputStreamclass implements a buffered outputstream. By setting up such an output stream, an application canwrite bytes to the underlying output stream without necessarilycausing a call to the underlying system for each byte written.

    Java.io.DataOutputStreamclass lets an application write primitiveJava data types to an output stream in a portable way. Anapplication can then use a data input stream to read the data backin.

    Java.io.PrintStream class adds functionality to another outputstream, the ability to print representations of various data valuesconveniently.

  • 8/11/2019 IO Package

    27/42

    CHARACTER STREAMS

  • 8/11/2019 IO Package

    28/42

    Character Streams

    Java.io.Readerclass is a abstract class forreading character streams.

    protected Reader()

    protected Reader(Object lock)

    Java.io.Writerclass is a abstract class for

    writing to character streams. protected Writer()

    protected Writer(Object lock)

  • 8/11/2019 IO Package

    29/42

    InputStreamReader

    Java.io.InputStreamReaderclass 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)

  • 8/11/2019 IO Package

    30/42

    FileReader

    Java.io.FileReaderclass is a convenience class for readingcharacter files.

    The constructors of this class assume that the default characterencoding and the default byte-buffer size are appropriate.

    FileReader is meant for reading streams of characters. Forreading streams of raw bytes, use FileInputStream.

    Constructors:

    FileReader(File file)FileReader(FileDescriptor file)

    FileReader(String fileName)

  • 8/11/2019 IO Package

    31/42

    String Reader & String Writer

    Java.io.StringReaderclass is a character streamwhose source is a string

    StringReader()

    StringReader(int initialSize)

    Java.io.StringWriterclass is a character streamthat collects its output in a string buffer, which

    can then be used to construct a string. StringWriter()

    StringWriter(int initialSize)

  • 8/11/2019 IO Package

    32/42

    BufferedReader

    Java.io.BufferedReaderclass reads text from a character-input stream, buffering characters so as to provide for theefficient 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 bytestream.

    Constructors:

    BufferedReader(Reader in)

    BufferedReader(Reader in, int sz)

  • 8/11/2019 IO Package

    33/42

    BufferedWriter

    Java.io.BufferedWriterclass writes text to a character-output stream, buffering characters so as to provide for theefficient 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)

  • 8/11/2019 IO Package

    34/42

    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 anWriter.The buffer automatically grows when

    data is written to the stream.

  • 8/11/2019 IO Package

    35/42

    Java Serialization

    Java provides a mechanism, called object serialization where anobject can be represented as a sequence of bytes that includesthe object's data as well as information about the object's typeand the types of data stored in the object.

    After a serialized object has been written into a file, it can beread from the file and de-serialized that is, the type informationand bytes that represent the object and its data can be used torecreate 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.

  • 8/11/2019 IO Package

    36/42

    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.

  • 8/11/2019 IO Package

    37/42

    ObjectInputStream

    Java.io.ObjectInputStreamclass deserializes primitive dataand objects previously written using anObjectOutputStream. It is used to recover those objects previously serialized. It

    ensures that the types of all objects in the graph created fromthe stream match the classes present in the Java VirtualMachine.

    Classes are loaded as required using the standard mechanisms.

    Constructors:

    protected ObjectInputStream()

    ObjectInputStream(InputStream in)

  • 8/11/2019 IO Package

    38/42

    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)

  • 8/11/2019 IO Package

    39/42

    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. FileOutputStream6. FileInputStream

    5. FileWriter6. FileReader

    7. BufferedOutputStream

    8. BufferedInputStream

    7. BufferedWriter

    8. BufferedReader

    9. PrintStream 9. PrintWriter

    10. DataOutputStream11. DataInputStream

    10. No counterpart11. No counterpart

    12. ObjectOutputStream

    13. ObjectInputStream

    12. No counterpart

    13. No counterpart

  • 8/11/2019 IO Package

    40/42

    I/O Classes

  • 8/11/2019 IO Package

    41/42

    I/O ClassesTypes of I/O Stream Classes Type Description

    File

    File ReaderCharacter

    Used to read from &write to a file on filesystem

    FileWriter

    FileInputStream

    Byte

    FileOutputStream

    Memory

    CharArrayReader

    Character

    CharArrayWriter

    ByteArrayInputStream

    Byte

    ByteArrayoutputStream

    Data COnversion

    DataInputStream

    Byte

    DataoutputStream

    Buffering

    BufferedReader

    Character

    Buffer data while reading& writingReduce no of access

    require onoriginal datasourceMore efficientUsed with other streams

    BufferedWriter

    BufferedInputStream

    BufferedOutputStream

    Converting between bytes & streamsInputStreamReader

    Bridge b/w byte tocharacter streamOutputStreamWriter

    Byte

  • 8/11/2019 IO Package

    42/42


Recommended