790 likes | 800 Views
Learn how to process input and output in Java using streams, file handling, and standard I/O. Understand text and binary data formats, Java stream types, and important stream classes.
E N D
6.Streams and File I/O Miss.P.S.Dungarwal
Java I/O • Java I/O (Input and Output) is used to process the input and produce the output. • Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. • We can perform file handling in Java by Java I/O API.
Stream • A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. • In Java, a stream is a path along which the data flows. Every stream has a source and a destination. We can build a complex file processing sequence using a series of simple stream operations. Two fundamental types of streams are Writing streams and Reading streams. While an Writing streams writes data into a source(file) , an Reading streams is used to read data from a source(file).
Standard Streams All the programming languages provide support for standard I/O where the user's program can take input from a keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams− • Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in. Syntax public static final InputStream in • Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out. Syntax:public static final PrintStream out • Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err. Syntax: public static final PrintStreamerr
Text and Binary Formats of Data • There are two fundamentally different ways to store data. They are text format and binary format. Data items are stored in human-readable form in the text format. For example, the data item 85,050 is stored as the sequence of the five characters ‘8’ ‘5’ ‘0’ ‘5’ ‘0’. Data items are represented in bytes in the case of binary format. As a byte consists of 8 bits, it can represent one of 256 values. Since the data item 85,050 can be represented as the sequence of the four bytes 0, 1, 76, 58. If data items are available in text format, we have to use the Character stream classes to process the input and output. • If the data items are made available in binary format, we have to use the Byte stream classes. While the text format is convenient for humans, storage of data in binary format is more compact and more efficient.
Types of streamclass • Java encapsulates Stream under java.io package. Java defines two types of streams. They are, • Byte Stream : It provides a convenient means for handling input and output of byte. • Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.
1.Byte Streams classes • Java byte streams are used to perform input and output of 8-bit bytes.It provides a convenient means for handling input and output of byte. • Though there are many classes related to byte streams but the most frequently used classes are, InputStream and OutputStream.
InPutStream − The InputStream is used to read data from a source. • OutPutStream − The OutputStream is used for writing data to a destination. • Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O
InputStream • Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket.
Input Stream class • InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
Output Stream class • OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
2.Character Stream Classes • Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Reader stream classes • Reader stream classes that are used to read characters include a super class known as Reader and a number of subclasses for supporting various input-related functions. Reader stream classes are functionally very similar to the input stream classes, except input streams use bytes as their fundamental unit of information, while reader streams use characters. The Reader class contains methods that are identical to those available in the Input Stream class, except Reader is designed to handle characters. Therefore, reader classes can perform all the functions implemented by the input stream classes.
Writer Stream Classes • Like output stream classes, the writer stream classes are designed to perform all output operations on files. Only difference is that while output stream classes are designed to write bytes, the writer stream are designed to write character. The Writer class is an abstract class which acts as a base class for all the other writer stream classes. This base class provides support for all output operations by defining methods that are identical to those in Outputstream class.
1.RandomAccessFile • Using a random access file, we can read from a file as well as write to the file. • Reading and writing using the file input and output streams are a sequential process. • Using a random access file, we can read or write at any position within the file. • An object of the RandomAccessFile class can do the random file access. We can read/write bytes and all primitive types values to a file. • RandomAccessFile can work with strings using its readUTF() and writeUTF() methods. • The RandomAccessFile class is not in the class hierarchy of the InputStream and OutputStream classes. • RandomAccessFile(File file, String mode) This creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
Mode A random access file can be created in four different access modes. The access mode value is a string. They are listed as follows:
DataInput Interface The data input interface is implemented by streams that can read primitive Java data types from a stream in a machine-independent manner. Reads a boolean value from the input stream. Reads a signed 8-bit value from the input stream.
DataInput’s methods can all throw IOExceptions. They are: .readBoolean( ) Reads one byte and returns true or false if it was zero or non-zero. .readByte( ) Reads and returns a byte. .readChar( ) Reads and returns a char. .readDouble( ) Reads eight bytes and returns a double. .readFloat( ) Reads four bytes and returns a float. .readFully( byte[ ] ) Reads bytes into an array. .readFully( byte[ ], offset, len) Reads len bytes into an arry starting at offset. .readInt( ) Reads four bytes and returns an int. .readLine( ) Reads the next line of text from the input stream. .readLong( ) Reads eight bytes and returns a long. .readShort( ) Reads two bytes and returns a short. .readUnsignedByte( ) Reads a byte, extends it to int, and returns it in the range 0 to 255. .readUnsignedShort( ) Reads two bytes and returns an int in the range 0 to 65535. .readUTF( ) Reads in a String that has been encoded using a modified UTF-8 format. .skipBytes( num ) Skips num bytes of the input stream.
DataOutput Interface • DataOutput is the interface which defines basic methods for the byte output streamclasseslisted above. • The DataOutput interface defines fourteen methods for converting Java primitives and String types to raw bytes and then writing them to a byte stream.
The DataOutput methods are: write( int ) - Writes the eight low-order bits of an int. write( byte[ ] ) - Writes all the bytes in a byte array. write( byte[ ], offset, len ) - Writes len bytes from a byte array starting at offset off. writeBoolean( boolean ) - Writes a one-byte boolean value. writeByte( int ) - Acts the same as write( int b ) above writeBytes( String ) - Writes the low order bytes of all the characters in a String. writeChar( int ) - Writes a two-byte char value from the low end of an int. writeChars( String ) - Writes the two char bytes of all the characters in a String. writeDouble( double ) - Writes an eight-byte double value. writeFloat( float ) - Writes a four-byte float value. writeInt( int ) - Writes a four-byte int value. writeLong( long ) - Writes an eight-byte long value. writeShort( int ) - Writes a two byte short value from the low end of an int. writeUTF( String ) - Writes the characters of the String in special modified UTF format so readUTF(...) can read them back.
2.StreamTokenizer • Breaking a string or stream into meaningful independent words is known as tokenization. Tokenization is a common practice to tool developers. java.util package includes StringTokenizer which tokenizes a string into independent words. For StringTokenizer, the source is a string. There comes a similar tokenizer, StreamTokenize with java.io package for which source is a stream. Here, the StreamTokenizer tokenizes a whole stream into independent words.
For StreamTokenizer, the source is a character stream, Reader. StreamTokenizer tokenizes the stream into distinct words and allows to read one by one. It is not a general tokenizer and includes the capability of knowing the type of the token like the token is a word or number. For general tokenization, there comes java.util.Scanner where each word or line can read with next(), nextLine() and nextUTF() methods. StreamTokenizer includes a method nextToken() that can be used in a for loop to print all the tokens.
The StreamTokenizer comes with the following constant variables (instance variables are also known as fields) used to decide the type of the token. • intttype: When the nextToken() returns a token, this field can be used to decide the type of the token. • static final int TT_EOF: This field is used to know the end of file is reached. • static final int TT_EOL: This field is used to know the end of line is reached. • static final int TT_NUMBER: This field is used to decide the token returned by the nextToken() method is a number or not. • static final int TT_WORD: This field is used to decide the token returned by the nextToken() method is a word or not. • String sval: If the token is a word, this filed contains the word that can be used in programming. • double nval: If the token is a word, this filed contains the number that can be used in programming. • Following is the class signature public class StreamTokenizer extends Object
File Class • Java File class is a part of java.io package. • Java File class is an abstract representation of file and directory pathnames. • Operating systems uses system dependent pathnames to represent the file and directories but the java File class presents an abstract, system independent view of pathnames. This conversion of pathnames to or from an abstract pathname is inherently system dependent. • The parent of abstract pathname can bet fetch by calling getParent() method of File class.
Java File Constructors • We can create an instance of File class using below constructors. • File(File parent, String child): Using this constructor we can create an instance of File class from specified parent abstract pathname and a child pathname string. • File(String pathname): Using this constructor we can create an instance of File class from specified string pathname by converting it into an abstract pathname. • File(String parent, String child): Using this file constructor we can create an instance of File class from specified parent and child pathname. • File(URI uri): We can create an instance of File class from specified URI by converting it into abstract pathname.
canExecute(): This method tests if an application can execute the file that is denoted by this abstract pathname and returns either true or false. • canRead(): This method tests if an application can read the file that is denoted by this abstract pathname and returns either true or false. • canWrite(): This method tests if an application can modify the file that is denoted by this abstract pathname and returns either true or false. • compareTO(File pathname): This method compare two abstract pathnames lexicographically and returns integer value. • createNewFile(): This method automatically creates new empty file named by this abstract pathname if and only if a file with this name does not exist and returns either true or false.
createTempFile(String prefix, String suffix): This is a static method and creates an empty file in the default temporary-file directory using specified prefix and suffix strings to generate file name and returns file object. • createTempFile(String prefix, String suffix, File directory): This is a static method and creates an empty file in specified directory using specified prefix and suffix strings to generate file name and returns file object. • delete(): This method deletes the file or directory denoted by this abstract pathname and returns either true or false. • deleteOnExit(): This method requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates and this is void method. • exists(): This method checks whether the file or directory denoted by this abstract pathname is exists or not and based one that it will returns either true or false. • getAbsoluteFile(): This method returns the absolute form of this abstract pathname.
getAbsolutePath(): This methods returns absolute pathname string of this abstract pathname. • getCanonicalFile(): This method returns canonical form of this abstract pathname. • getCanonicalPath(): This method returns canonical pathname string of this abstract pathname. • getName(): This method returns the name of file or directory denoted by this abstract pathname. • isDirectory(): This method checks if the file denoted by this abstract pathname is directory or not and based on that it will returns either true or false. • isFile(): This method checks if the file denoted by this abstract pathname is normal file or not and based on that it will return either true or false. • isHidden(): This method checks if the file denoted by this abstract pathname is hidden file or not and based on that it will return either true or false. • list(): This method returns an array of strings which contains naming of file or directories in the directory denoted by this abstract pathname. • listFiles(): This method returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
mkdir(): This method creates the directory named by this abstract pathname and returns either true or false. • renameTo(File dest): This method renames the file denoted by this abstract pathname and returns either true or false. • setReadable(boolean readable): This method sets owner’s read permission for this abstract pathname and returns either true or false. • setReadable(boolean readable, boolean ownerOnly): This method sets owner’s or everybody’s read permission for this abstract pathname and returns either true or false. • setReadOnly(): This method marks he file or directory named by this abstract pathname so that only read operation s are allowed and it returns either true or false. • setWritable(boolean writable): This method sets owner’s write permission for this abstract pathname and returns either true or false
FileInputStream • The Java.io.FileInputStream class obtains input bytes from a file in a file system. What files are available depends on the host environment. Following are the important points about FileInputStream − • This class is meant for reading streams of raw bytes such as image data. • For reading streams of characters, use FileReader. Constructor:- • FileInputStream(File file) This creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. • FileInputStream(String name) This creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
FileOutputStream • The Java.io.FileOutputStream class is an output stream for writing data to a File or to a FileDescriptor. Following are the important points about FileOutputStream − • This class is meant for writing streams of raw bytes such as image data. • For writing streams of characters, use FileWriter. • FileOutputStream(File file, boolean append) This creates a file output stream to write to the file represented by the specified File object. • FileOutputStream(FileDescriptorfdObj) This creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system. • FileOutputStream(String name) This creates an output file stream to write to the file with the specified name.
Serialization • It is a mechanism of writing the state of an object into a byte stream. • It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. • The reverse operation of serialization is called deserialization. • It is mainly used to travel object's state on the network (which is known as marshaling).