SlideShare a Scribd company logo
Chapter 19  Binary Input & Output   Java I  ITP 120
Chapter  Objectives To understand how I/O is handled in Java  To distinguish between text I/O and binary I/O  To read and write bytes using  FileInputStream  and  FileOutputStream  To read and write primitive values and strings using the  DataInputStream and DataOutputStream  classes To store and restore objects using  ObjectOutputStream  and  ObjectInputStream , and to understand how objects are serialized and what kind of objects can be serialized  To use the  Serializable  interface to enable objects to be serializable  (optional) To know how to serialize arrays  (optional) To use  RandomAccessFile  for both read and write (Optional).
Overview The  java.io.*  package provides a library of classes to read and write various  types of data. In Java, all data I/O is  handled in the form of  streams Data streams can be  byte streams  or  character streams   The  java.io  package has classes that process  byte  streams of all types NOTE:  In Java, a character is  2 BYTES !  Also NOTE:  a Unicode character is 2 bytes ! The  Reader  and  Writer  classes process  character  streams. Streams can be layered, so that one type of streams can be converted to another type of streams by  chaining .  Chaining  a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .
Overview  ---  Streams A  stream  is an abstraction of a  continuous  one-way flow of data .
2 Types of Stream Classes:  Bytes & Characters The stream classes can be categorized into two types:  byte streams  and  character streams . The  InputStream/OutputStream  class is the root of all  BYTE  stream classes The  Reader/Writer  class is the root of all  CHARACTER  stream classes. The subclasses of  InputStream/OutputStream  are analogous to the  subclasses of  Reader/Writer .
Byte Stream Classes  (note: the word “stream” )
Character Stream Classes  (Character = 2 bytes)
How is I/O Handled in Java? A  File  object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.  Formatter output = new Formatter("temp.txt"); output.format("%s", "Java 101"); output.close(); Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());
Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a  byte -type value  C7  in a binary file, because decimal  199  equals to hex  C7 .
Binary I/O Text I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Binary I/O Classes
The value returned is a byte as an int type. InputStream
The value is a byte as an int type. OutputStream
FileInputStream/FileOutputStream FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
FileInputStream To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A  java.io.FileNotFoundException  would occur if you attempt to create a  FileInputStream  with a nonexistent file.
FileOutputStream To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append)    If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.  TestFileStream Run
FilterInputStream/FilterOutputStream Filter streams  are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters.  FilterInputStream  and  FilterOutputStream  are the base classes for filtering data. When you need to process primitive numeric types, use  DatInputStream  and  DataOutputStream  to filter bytes.
DataInputStream/DataOutputStream DataInputStream  reads bytes from the stream and converts them into appropriate primitive type values or strings.  DataOutputStream  converts primitive type values or strings into bytes and output the bytes to the stream.
DataInputStream DataInputStream  extends  FilterInputStream  and implements the  DataInput  interface.
DataOutputStream DataOutputStream  extends  FilterOutputStream  and implements the  DataOutput  interface.
Characters and Strings in Binary I/O   A Unicode consists of two bytes. The  writeChar(char c)  method writes the Unicode of character  c  to the output. The  writeChars(String s)  method writes the Unicode for each character in the string  s  to the output. Why UTF-8? What is UTF-8? UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.
Using  DataInputStream / DataOutputStream   Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream)   The statements given below create data streams. The first statement creates an input stream for file  in.dat ; the second statement creates an output stream for file  out.dat . DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); TestDataStream Run
Checking End of File TIP: If you keep reading data at the end of a stream, an  EOFException  would occur. So how do you check the end of a file? You can use  input.available()  to check it.  input.available() == 0  indicates that it is the end of a file. Order and Format CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using  writeUTF , you must read names using  readUTF .
BufferedInputStream/ BufferedOutputStream Using buffers to speed up I/O  BufferedInputStream / BufferedOutputStream  does not contain new methods. All the methods  BufferedInputStream / BufferedOutputStream  are inherited from the  InputStream / OutputStream  classes.
Constructing  BufferedInputStream / BufferedOutputStream   // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize)   // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize)
Case Studies: Copy File  This case study develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command: java Copy source target   The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists.  Copy Run
Object I/O DataInputStream / DataOutputStream  enables you to perform I/O for primitive type values and strings.  ObjectInputStream / ObjectOutputStream  enables you to perform I/O for objects in addition for primitive type values and strings.  Optional
ObjectInputStream ObjectInputStream  extends  InputStream  and implements  ObjectInput  and  ObjectStreamConstants .
ObjectOutputStream ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
Using Object Streams You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in)   // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out)  TestObjectOutputStream Run TestObjectInputStream Run
Random Access Files All of the streams you have used so far are known as  read-only  or  write-only  streams. The external files of these streams are  sequential  files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the  RandomAccessFile  class to allow a file to be read from and write to at random locations.
RandomAccessFile
File Pointer A random access file consists of a sequence of bytes. There is a special marker called  file pointer  that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an  int  value using  readInt() , the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.
RandomAccessFile  Methods Many methods in  RandomAccessFile  are the same as those in  DataInputStream  and  DataOutputStream . For example,  readInt() ,  readLong() ,  writeDouble() ,  readLine() ,  writeInt() ,  and  writeLong()  can be used in data input stream or data output stream as well as in  RandomAccessFile  streams.
RandomAccessFile  Methods, cont. void seek(long pos) throws IOException; Sets the offset from the beginning of the  RandomAccessFile  stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.
RandomAccessFile  Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first. final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.
RandomAccessFile  Constructor RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); //read only
Case Studies: Address Book Now let us use  RandomAccessFile  to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The  Add  button stores a new address to the end of the file. The  First ,  Next ,  Previous , and  Last  buttons retrieve the first, next, previous, and last addresses from the file, respectively. Optional
Fixed Length String I/O Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks. FixedLengthStringIO
End of Presentation Binary Input & Output   Chapter 18
How is I/O Handled in Java? A  File  object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.  Formatter output = new Formatter(“outfile.txt"); output.format("%s", "Java 120");  // Write a string to outfile.txt output.close();  // Close the output file  outfile.txt Scanner input = new Scanner(new File("temp.txt"));  // Create object System.out.println(input.nextLine());  // Read a line
Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form.  You   cannot read binary files.  Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM.  The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a  sequence of characters  and a binary file consists of a  sequence of bits.  For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a  byte -type value  C7  in a binary file ( Note: decimal  199  equals to Hex  C7 .)
Binary File I/O Text I/O requires encoding and decoding.  The JVM converts a Unicode char to a file-specific encoding when writing a character and coverts a file-specific encoding to a Unicode char when reading a character.  Binary I/O does not require conversions . When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Binary I/O Classes  Inheritance Hierarchy
The value returned is a byte as an int type. InputStream (a byte stream class)
The value is a byte as an int type. OutputStream ( a byte stream class)
FileInputStream & FileOutputStream (byte streams) FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
FileInputStream (byte stream) To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A  java.io.FileNotFoundException  would occur if you attempt  to create a  FileInputStream  with a nonexistent file.
FileOutputStream (byte stream) To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append)  // append = true  to add on to the file    If the file  does not exist , a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing  true  to the append parameter. Demo Program:  TestFileStream.java
FilterInputStream/FilterOutputStream Filter streams  are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class  enables you to read integers, doubles,   and strings  instead of bytes and characters.  FilterInputStream  and  FilterOutputStream  are the base classes for filtering data. When you need to process primitive numeric types, use  DataInputStream  and  DataOutputStream  to filter bytes.
DataInputStream & DataOutputStream (byte streams) DataInputStream  reads bytes from the stream and converts them into appropriate primitive type values or strings.  DataOutputStream  converts primitive type values or strings into bytes and outputs the bytes to the stream.
DataInputStream ( byte stream) DataInputStream  extends  FilterInputStream  and implements the  DataInput  interface.
DataOutputStream (byte stream) DataOutputStream  extends  FilterOutputStream  and implements the  DataOutput  interface.
Characters and Strings in Binary I/O   A Unicode char is 2 bytes. The  writeChar(char ch)  method writes the Unicode of character  ch  to the output. The  writeChars(String str)  method writes the Unicode for each character in the string  str  to the output file. What  is  UTF-8 ?  Why use UTF-8 ?  [  UTF  means Unicode Text File ] UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) (127 decimal) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in  three  bytes.
Using  DataInputStream / DataOutputStream   Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream)   The statements below create data streams. The first statement creates an input stream for file  in.dat ;  the second statement creates an output stream for file  out.dat . DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); Demo Program:  TestDataStream.java
Checking for the End of File (EOF) TIP: If the program tried to read data at the end of a stream, an  EOFException  would occur. How do you check the end of a file?  Use  input.available()  to check for EOF. if  input.available() == 0  then the program is at  the end of a file. (EOF) Order and Format CAUTION: You have to read the data in the same order and same format in which they are stored. For example, if names are written in UTF-8 using  writeUTF (String  str) , you  MUST  read the names using the  readUTF  method.
BufferedInputStream/ BufferedOutputStream Use buffers to speed up I/O processes BufferedInputStream / BufferedOutputStream  does not contain new methods. All the methods  BufferedInputStream / BufferedOutputStream  are inherited from the  InputStream / OutputStream  classes.
Constructing  BufferedInputStream / BufferedOutputStream   // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize)   // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStream out, int bufferSize)
CopyFile.java CopyFile.java is  a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command: java CopyFile  source target Also: java CompFile  source target   The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists.
Object I/O  (optional) DataInputStream / DataOutputStream  enables you to perform I/O for primitive type values and strings.  ObjectInputStream / ObjectOutputStream  enables you to perform I/O for objects in addition for primitive type values and strings.
ObjectInputStream (optional) ObjectInputStream  extends  InputStream  and implements  ObjectInput  and  ObjectStreamConstants .
ObjectOutputStream (optional) ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
Using Object Streams (optional) You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in)   // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out)  Demo:   TestObjectOutputStream.java TestObjectInputStream.java
The  Serializable  Interface Not all objects can be written to an output stream. Objects that  CAN  be written to an object stream is said to be  serializable . A serializable object is an instance of the  java.io.Serializable  interface. So the class of a serializable object must implement the  Serializable  interface. The  Serializable  interface is a  marker interface .  It has no methods, so you don't need to add additional code in your class that implements  Serializable . Implementing this interface enables the Java serialization mechanism  to automate the process of storing the objects and arrays.
The  transient  Keyword If an object is an instance of  Serializable , but it contains  non-serializable instance data fields , can the object be serialized?  The answer is NO ! To enable the object to be serialized, you can use the  transient  keyword to mark these data fields to tell the JVM to  ignore  these fields when writing the object to an object stream.
The  transient  Keyword, cont. Consider the following class:   public class ITP120 implements java.io.Serializable {  private int v1; private static double v2; private transient  A  v3 = new A();  } class A { } // A is not serializable   When an object of the ITP120 class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.
Serializing Arrays (optional)   An array is serializable if all its elements are serializable. So an entire array can be saved using  writeObject  into a file and later restored using  readObject .  Listing 18.6 stores an array of five  int  values,  an array of three strings, and an array of two  JButton  objects, and reads them back to display on the console. Demo Program:  TestObjectStreamForArray.java
Random Access Files All of the streams you have used so far are known as  read-only  or  write-only  streams. The external files of these streams are  sequential  files that cannot be updated without creating a new file.  It is often necessary to modify files or to insert new records into files. Java provides the  RandomAccessFile  class to allow a file to be read from and write to at random locations.
RandomAccessFile
File Pointers A random access file consists of a sequence of bytes. There is a special marker called  file pointer  that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file,  the file pointer moves forward to the next data . For example, if you read an  int  value using  readInt() ,  the JVM reads  four bytes  from the file pointer and now the file pointer is four bytes ahead of the previous location.
File Pointers  (moving the pointer 4 bytes ahead)
RandomAccessFile   Methods Many methods in  RandomAccessFile  are the same as those in  DataInputStream  and  DataOutputStream .  For example,  readInt() ,  readLong() ,  writeDouble() ,  readLine() ,  writeInt() ,  and  writeLong()   can be used in data input stream or data output stream as well as in  RandomAccessFile  streams.
RandomAccessFile   Methods, cont. void seek(long pos) throws IOException; Sets the offset from the beginning of the  RandomAccessFile  stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.
RandomAccessFile   Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first. final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.
RandomAccessFile  Constructors RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //allows read and write to the file RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); //read only Demo program:  TestRandomAccessFile.java (uses FixedLengthStringIO.java)
Case Study: Address Book Now let us use  RandomAccessFile  to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The  Add  button stores a new address to the end of the file. The  First ,  Next ,  Previous , and  Last  buttons retrieve the first, next, previous, and last addresses from the file, respectively. Run:  AddressBook.java  which uses FixedLengthStringIO.java
Fixed Length String I/O Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks. FixedLengthStringIO
Chapter 18 Demo Programs ReadBytes.java (skip)  WriteData.java WriteDemo.java  ReadData.java ShowFile.java CopyFile.java  CopyFileUsingByteStream.java CompFile.java  RWData.java RandomAccessDemo.java PrintWriterDemo.java ReadChars.java  or BuffReader.java ReadLines.java  (BufferedReader)
Chapter 18 Demo Programs TextFileScannerDemo.java  Uses input file  morestuff.txt   HasNextLineDemo.java Uses input file  original.txt and creates output file  numbered.txt BufferReaderDemo.java Uses input file:  buffer.txt
Chapter 18 Demo Programs TestDataStreams.java TestFileClass.java TestPrintWriters.java ViewFile.java  (GUI text file viewer program) needs MyFrameWithExitHanding.java  class file ParsingTextFile.java  (needs  grades.dat  file) (creates  gradesout.dat) TestRandomAccessFile.java  AddressBook.java  (creates file  address.dat) needs  FixedLengthStringIO.class  file
Chapter 18  Demo Programs TestDataStream.java TestFileReader.java  (needs temp.txt) TestFileStream.java  TestFileWriter.java  (needs testdata.txt) TestObjectStreamForArray.java  ( creates array.dat) TestObjectOutputStream.java  (creates  object.dat) TestObjectInputStream.java  (reads object.dat)
Chapter 18  Input / Output  Optional: More on Java File I/O   Chapter 18  Java I  ITP 120
Chapter 18:  More on Input and Output  Stream Classes  (byte & character streams) Predefined Streams (System.in, System.out, System.err) Processing External Files Data Streams Print Streams Buffered Streams Text Input and Output on the Console Random Access Files
Chapter 18  Input /Output  Objectives Understand input & output streams and learn how to create them. Discover the uses of  byte  and  character  streams. To know how to  read from  /  write to  external files using file streams. To become familiar with the  File  class. To use print streams to output data of primitive types in text  format. To know how to  read and write text data  files . Use  text input and output  on the console. Use  RandomAccessFile  for reading & writing random access files.
Overview The  java.io.*  package provides a library of classes to read and write various  types of data. In Java, all data I/O is  handled in the form of  streams Data streams can be  byte streams  or  character streams   The  java.io  package has classes that process  byte  streams of all types NOTE:  In Java, a character is  2 BYTES !  NOTE:  Unicode character is 2 bytes ! The  Reader  and  Writer  classes process  character  streams. Streams can be layered, so that one type of streams can be converted to another type of streams by  chaining .  Chaining  a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .
Overview  Streams In Java, all  Input/Output   is handled by  streams A stream is an abstraction of the continuous  one-way  flow of data Java streams can be applied to any source of data, so it is easy to get input from the keyboard and send output to a monitor, and the same applies to file input & output. All streams EXCEPT  random-access file streams  flow only in one direction. See the diagram on the next slide  
Overview  ---  Streams A  stream  is an abstraction of a  continuous  one-way flow of data .
Overview and Background The  original  version of Java defined  only the byte   stream , but  character streams  were quickly added. Byte streams  can be used when reading or writing  binary  data. Character streams  are designed for handling  character  I/O. Character streams  use  UNICODE .  In Java, a  character is  2  bytes   Unicode  is for the internationalization of Java in  different languages . The Java I/O system is quite LARGE  because of the  TWO separate class hierarchies of bytes and streams.
How is I/O Handled in Java? A  File  object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.  Formatter output = new Formatter("temp.txt"); output.format("%s", "Java  ITP 120"); output.close(); Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());
Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files.  Binary files are designed to be read by programs . For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a  byte -type value  C7  in a binary file, because decimal  199  equals to hex  C7   ( 12  x  16 + 7  = 192 + 7 = 199 decimal )
Binary I/O Text I/O requires encoding and decoding. The JVM converts a Unicode character to  file-specific encoding when writing a character, and coverts a file-specific encoding to a Unicode character when reading a character.  Binary I/O does not require conversions . When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
2 Types of Stream Classes:  Bytes & Characters The stream classes can be categorized into two types:  byte streams  and  character streams . The  InputStream/OutputStream  class is the root of all  byte  stream classes The  Reader/Writer  class is the root of all  character  stream classes. The subclasses of  InputStream/OutputStream  are analogous to the  subclasses of  Reader/Writer .
Byte Stream Classes  (note: “stream” )
Character Stream Classes  (Character = 2 bytes)
Predefined Streams in Java All Java programs automatically import the  java.lang  package. The  java.lang   package defines a class called  System  which encapsulates several aspects of the runtime environment. The System class contains  3  predefined  stream variables called: in, out, and err  (System.in, System.out, System.err) These variables are declared as  public  and  static  with the  System  class.  This means they can be used by any other part of your program and  without  a reference to a specific object in the System class.
Predefined Streams in Java:  System class System.in  refers to the standard  input  stream which is the keyboard by default.  (Keyboard ) System.out  refers to the standard  output  stream which is the console by default.  (Monitor) System.err  refers to the standard  error  stream which is also the console by default.  (Monitor) These streams may be redirected to  any compatible I/O device .
Predefined Streams in Java:  System class System.in  is an object of type InputStream.  (byte stream) System.out  is an object of type PrintStream. (byte stream) System.err  is an object of type PrintStream. (byte stream) They are all  byte streams  and are a part of the original Java specification. They are NOT  character  streams ! (Unicode character = 2 bytes)
Reading Keyboard Input // Read an array of bytes from the keyboard.  import java.io.*;  public class ReadBytes {  public static void main(String[ ]  args)  throws IOException {  byte data[ ] = new byte[10];  // Byte array  “data” holds 10 bytes System.out.println(&quot;Enter some characters:&quot;);  System.in.read(data);  //  Use the “read” method to read some bytes System.out.print(&quot;You entered: &quot;);  for(int i=0; i < data.length; i++)  System.out.print((char) data[i]);  // Cast data to a character }  // End main method } // End class ReadBytes
Reading Keyboard Input  Here is a sample run from the  previous  program: Enter some characters:  (prompt from program) READ BYTES   (User entered READ BYTES) You entered:  READ BYTES  (output from program)
Writing Output to the Monitor // Demonstrate System.out.write().  Java program  WriteDemo.java public class WriteDemo  {  public static void main(String[ ]  args)  {  int b;    // Program prints an ‘X’ on the monitor b = 'X';  // The character is an  int  System.out.write(b);  //  A byte stream; write low-order 8 bits System.out.write('\n');  // Print a newline character  \n }  // End of main( )  // print() and println() are easier to use than write() }  // End of class WriteDemo
Stream classes  (Bytes & Characters) The  java.io  package provides two categories of classes: Byte stream readers and writers Character stream readers and writers At the top of the hierarchy for stream classes are the abstract classes InputStream and Output Stream  The subclasses branch out and specializes into the different types of streams that they handle. InputData, OutputData, and ObjectInput  interfaces  are implemented by the classes that handle data, such as , int, double, char,  etc., and objects.  Only ObjectInput specifies methods for reading objects. DataInputStream -  which is a subclass of FilterInputStream, which in turn is a subclass of InputStream – implements the InputData interface and can read primitive data, and objects from byte streams.
Stream Classes FileInputStream  can read raw streams of data from files. DataOutputStream  can write primitive data; this class implements the  OutputData  interface RandomAccessFile  implements both  InputData  and  OutputData  interfaces, therefore, it can read and write data to streams. ObjectOutputStream  implements the  ObjectOutput  interface and can write object data to streams.
InputStream Class  (for reading bytes) The following methods are defined in InputStream  and are often useful: public abstract int read() throws IOException Reads the next byte and returns its value in the range of 0 to 255.  At the end of the stream, it returns a  - 1. public int read(byte b[]) throws IOException Reads bytes into array b,, returns b.length if the  number of available bytes is >= b.length.  Returns the number of bytes read if the number of available bytes is < than b.length, and returns –1 at the end of the stream.
InputStream Class  (for reading bytes) The following methods are defined in InputStream and are often useful: public void close() throws IOException This method closes the input stream. public void available() throws IOException Returns the number of bytes that can be read from the input stream without blocking.
InputStream Class  (for reading bytes) The following method is defined in InputStream and is often useful: public long skip(long n) throws IOException Skip over and discard  n bytes of data from the input stream.  The actual number of bytes skipped is returned.
Reading & Writing Files Using Byte Streams To create a byte stream linked to a file, use  FileInputStream  or  FileOutputStream To open a file, create an object of one of these classes, specifying the  name of the file  as an  argument  to the  constructor . Once the file is open, you can read from the file or write to the file. To read form a file, you may use  the  read( )  method. int read( ) throws IOException When you are done with a file, you should close it by calling  close() void close( ) throws IOException Closing a file releases the system resources allocated to the file, allowing them to be used by another file.
Reading & Writing Files Using Byte Streams /* Display a text file.  To use this program, specify the name  of the file that you want to see.  For example, to see a file called TEST.TXT,  use the following command line.  Command line usage:  java  ShowFile  TEST.TXT  */ //  Program ShowFile.java  follows on the next slide  ->
Reading & Writing Files Using Byte Streams public class ShowFile {  public static void main(String[ ]  args)  throws IOException  { int i;  FileInputStream fin;  // Declare file pointer try {  fin = new  FileInputStream(args[0]);  }  // Open the input file catch(FileNotFoundException exc) {  System.out.println(“Error: “ + exc.getMessage( )); System.out.println(&quot;File Not Found&quot;);  return; } } catch(ArrayIndexOutOfBoundsException exc) {  System.out.println(“Error: “ + exc.getMessage( )); System.out.println(&quot;Usage is:  java ShowFile  File.txt &quot;);  return;  }
Reading & Writing Files Using Byte Streams // Read bytes until EOF is encountered  do {  i = fin.read( );  // Read an integer if(i != -1) System.out.print((char) i);  // Cast the int as a char } while( i  !=  -1);  // When  i  = -1,  EOF is encountered fin.close( );  // Close the input file }  // End of main method } // End of class ShowFile
Writing to a File Using Byte Streams /* Java program to Copy a text file.  To use this program, specify the name  of the source file and the destination file.  For example, to copy a file called File1.txt  to a file called File2.txt , use the following  on the command line: Usage:  java CopyFile  File1.txt  File2.txt  */
Writing to a File Using Byte Streams // CopyFile.java  Demo byte stream file operations import java.io.*;  public class CopyFile {  public static void main(String[ ]  args)  throws IOException  {  int i;  FileInputStream fin;  // Declare 2  byte stream files  (pointers) FileOutputStream fout;  // Output file pointer
Writing to a File Using Byte Streams try {  // outer try block //  try to open input file  try {  // inner try fin = new FileInputStream(args[0]);  } catch(FileNotFoundException exc) {  System.out.println(“Error:”  +  exc.getMessage( ) ); System.out.println(&quot;Input File Not Found&quot;);  return;  }
Writing to a File Using Byte Streams // open output file  try {  fout = new FileOutputStream(args[1]);  } catch(FileNotFoundException exc) {  System.out.println(“Error: “ + exc.getMessage()); System.out.println(&quot;Error Opening Output File&quot;);  return;  }  }  // End of outer try block
Writing to a File Using Byte Streams catch(ArrayIndexOutOfBoundsException exc) {  System.out.println(“Error: “ + exc.getMessage( ) ); System.out.println(&quot;Usage: CopyFile  File1  File2&quot;);  return;  } try {  //  Try to copy  file1 to file2 do {  i = fin.read( );  //  Read a byte if(i != -1)  fout.write(i);  // Write the byte to the output file } while(i  !=  -1);  // Loop while not at EOF (-1) }  // End of try block catch(IOException exc)  {  System.out.println(&quot;File Error&quot;);  } fin.close( );  // Close the input file fout.close( );  // Close the output file } // End of main( ) method  }  // End of class CopyFile
Reading & Writing Binary Data So far, we have been reading and writing bytes containing  ASCII  bytes. You may want to create a file that contains other types of data such as integers, doubles, or shorts , that is:  int, double, short,  etc. In Java, to  read and write binary values  of the simple Java data types, you  should  use: DataInputStream   and  DataOutputStream  (for  binary data) DataOutputStream implements the  OutputData interface . The  OutputData  interface defines methods that write all of Java’s simple data types to a file.
Reading & Writing Binary Data Note: Binary data is NOT in human-readable text format, obviously. The constructor for DataOutputStream is: DataOutputStream(OutputStream  outputStream ) outputStream  is the stream to which the  binary data  is written.
Reading & Writing Binary Data The constructor for DataInputStream is: DataInputStream(InputStream  inputStream ) inputStream  is the stream  that is linked to the instance of DataInputStream being created.  DataInputStream implements the  DataInput  interface which provides the methods for reading all of Java’s simple data types. DataInputStream uses an InputStream instance as its foundation, overlaying it with methods that read the various Java data types.
Reading & Writing Binary Data  Examples To create  an input stream for the file  in.dat  ( bytes) DataInputStream  infile = new DataInputStream(new FileInputStream(“in.dat”)); To create  an output stream for the file  out.dat: DataOutputStream  outfile = new DataOutputStream(new FileOutputStream(“out.dat”));
Reading & Writing Binary Data Common Input Methods Defined by  DataInputStream (a byte stream) Input Method Purpose boolean readBoolean ( )  Reads  a boolean byte readByte ( ) Reads a byte char readChar ( ) Reads a char double readDouble( ) Reads a double float readFloat ( ) Reads a float int readInt ( ) Reads an int long readLong ( ) Reads a long short readShort ( ) Reads a short
Reading & Writing Binary Data Common Output Methods Defined by  DataOutputStream ( byte stream) Output Method Purpose void writeBoolean (boolean val) writes the boolean specified by val void writeByte (int val) writes the low-order byte  val void writeChar(int val) writes the value val as a char void writeDouble(double val) writes the double val void writeFloat(float val) writes the float val void writeInt(int val) writes the int val void writeLong(long val) writes the long val void writeShort(int val) writes  val as a short
Reading & Writing Binary Data Here is a Java program that demonstrates  DataOutputStream  and  DataInputStream .  It writes and then reads back various types of data to and from a file. // Write and then read back binary data.  import java.io.*;  public class RWData {  public static void main(String[ ]  args)  throws IOException  {  DataOutputStream dataOut;  // Declare output, input file pointers DataInputStream  dataIn;
Reading & Writing Binary Data int i = 120;  double d = 1049.56;  boolean b = true;  try {  dataOut = new  DataOutputStream(new  FileOutputStream(“testdata&quot;));  } catch(IOException exc) {  System.out.println(“Error: “ + exc.getMessage( )); System.out.println(&quot;Cannot open file.&quot;);  return;  }
Reading & Writing Binary Data try {  // Write the binary data System.out.println(&quot;Writing &quot; + i);  dataOut.writeInt(i);  System.out.println(&quot;Writing &quot; + d);  dataOut.writeDouble(d);  System.out.println(&quot;Writing &quot; + b);  dataOut.writeBoolean(b);  System.out.println(&quot;Writing &quot; + 12.2 * 7.4);  dataOut.writeDouble(12.2 * 7.4);  }
Reading & Writing Binary Data catch(IOException exc) {  System.out.println(&quot;Write error: + exc.getMessage( )&quot;);  }  dataOut.close( );  System.out.println(); // Print a blank line // Now, read them back.  try {  dataIn = new  DataInputStream(new FileInputStream(&quot;testdata&quot;));  }  catch(IOException exc) {  System.out.println(&quot;Cannot open file. + exc.getMessage( )&quot;);  return;  }
Reading & Writing Binary Data try {  // Read the binary data i = dataIn.readInt();  System.out.println(&quot;Reading &quot; + i);  d = dataIn.readDouble();  System.out.println(&quot;Reading &quot; + d);  b = dataIn.readBoolean();  System.out.println(&quot;Reading &quot; + b);  d = dataIn.readDouble();  System.out.println(&quot;Reading &quot; + d);  }
Reading & Writing Binary Data catch(IOException exc) {  System.out.println(&quot;Read error.“ + exc.getMessage( ) );  } dataIn.close();  }  // End of main ( ) }  // End of class RWData The output from the previous program follows: Writing 120 Reading 120 Writing 1023.56 Reading 1049.56 Writing true Reading true Writing 90.28 Reading 90.28
Reader  class methods for reading  characters The  Reader  class is similar to the  InputStream  class. The methods in  Reader  are subject to character interpretation. Remember:  A character is 2 bytes ! public abstract int read() throws IOException public int read(char b[]) throws  IOException public void close() throws IOException public void skip() throws IOException
OutputStream ( bytes) & Writer (for characters) Like InputStream (for reading  bytes ) and Reader (for reading  characters ), OutputStream and Writer are the counterparts.  They are the base classes for for  all output streams  of bytes and characters, respectively. The next slide shows methods which are in both  OutputStream  and  Writer .   See next slide  ->
OutputStream  (Writing bytes) public abstract void write(int b) throws IOException Write a byte b (for OutputStream) or a charcter (for Writer) public void write(byte[] b) throws IOException This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer) public void close() throws IOException This method closes the output stream. public void flush() throws IOException Flush the output stream and send any buffered data in the stream to its destination.
Writer  (Writing characters)  (Same as OutputStream) public abstract void write(int b) throws IOException Write a byte b (for OutputStream) or a character (for Writer) public void write(byte[] b) throws IOException This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer) public void close() throws IOException This method closes the output stream. public void flush() throws IOException Flush the output stream and send any buffered data in the stream to its destination.
Console Input using Character Streams For Java code that will be internationalized, inputting data from the console  using Java’s character-based streams is a better ,  more convenient way  to read characters from the keyboard than using byte streams. Since  System.in  is a byte-stream, you need to wrap  System.in  inside of some type of  Reader . The best class for reading console input is  BufferedReader  which supports a buffered input stream.  (BufferedReader inherits from Reader) But, you cannot construct a  BufferedReader  directly from  System.in
Console Input using Character Streams You must first convert  the input from System.in from a byte stream into a character stream.   To do this, you must use InputStreamReader. InputStreamReader  converts bytes to characters. To obtain an InputStreamReader object that is linked to  System.in , use the following constructor: InputStreamReader ( InputStream  inputStream  ) Since System.in refers to an object of type InputStream, it can be used for  inputStream  such as in:  InputStreamReader(System.in)
Console Input using Character Streams Next, using the object produced by InputStreamReader, construct  a BufferedReader using the following constructor: BufferedReader(Reader  inputReader ) Here , inputReader  is the stream that is linked to the instance of BufferedReader being created.
Console Input using Character Streams Putting it all together, the following line of code creates a  BufferReader  that is connected to the keyboard. BufferedReader  br = new BufferedReader( new InputStreamReader(System.in)); After the above statement executes,  “br” will be a  character -based  stream that is linked to the console thru  System.in  (which reads bytes)
Console Input using Character Streams Reading Characters Characters can be read from  System.in  using the  read( )  method defined by BufferedReader. BufferedReader defines the following versions of  read( ) int read( ) throws IOException int read(char  data[ ] )  throws IOException int read(char  data[ ], int start, int max) throws IOException
Console Input using Character Streams int read( ) throws IOException reads a single Unicode character  and returns a  -1 when the end of the stream is reached. int read(char  data [ ])  throws IOException reads characters from the input stream until: (1) the array is full, (2) EOF is reached, or (3)  an error occurs. int read(char  data [ ], int  start , int  max ) throws IOException reads input into array  data  beginning at the location specified by  start , storing up to  max  characters.  It returns the number of characters read  or  -1 when the end of the stream is reached.  Pressing the [Enter] key generates an end-of-stream condition.
Console Input using Character Streams The following program demonstrates the  read( )   method by reading characters from the console until the user types a period. // Use a BufferedReader to read characters from the console.  import java.io.*;  public class ReadChars {  public static void main(String[ ]  args)  throws IOException  {
Console Input using Character Streams BufferedReader br = new  BufferedReader(new InputStreamReader(System.in));  System.out.println(&quot;Enter some characters; period to quit.&quot;);  // read characters  do {  c = (char) br.read();  // Cast the  character to a byte System.out.println(c);  // Print the character } while(c != '.');  // Loop as long as the input char is not a period }  // End of main  method }  // End of ReadChars  class
Console Input using Character Streams Output from the previous program could be: Enter some characters;  period to quit. I T P J A V A .  <-  note the period character which stopped  the input stream
Console Input using Character Streams Reading Character Strings from the Keyboard … To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.  The general form is: String readLine( )  throws IOException It returns a string object that contains the characters read. It returns  null  if an attempt is made to read beyond the end of the stream.
Console Input using Character Streams The following program demonstrates BufferedReader and the readLine() method.  The program reads and displays lines of text until the user enters the word  “stop” // Read a string from console using a BufferedReader.  import java.io.*;  class ReadLines {  public static void main(String[ ]  args)  throws IOException  {  // create a BufferedReader using System.in  BufferedReader br = new BufferedReader(new  InputStreamReader(System.in));  String str;
Console Input using Character Streams System.out.println(&quot;Enter lines of text.&quot;);  System.out.println(&quot;Enter 'stop' to quit.&quot;);  do {  str = br.readLine();  System.out.println(str);  } while(!str.equals(&quot;stop&quot;));  }  // End of main method }  // End of class ReadLines
Console  Output  using Character Streams The preferred method of writing to the console (monitor) when using Java is through a  PrintWriter  stream.  PrintWriter  is one of the character-based classes. Using a character-based class makes it easier to internationalize  Java programs. PrintWriter  has several constructors, but this is the one to be used in the demonstration program which is on the following slides: PrintWriter(OutputStream  outputStream , boolean flushOnNewline)
Console Output using Character Streams PrintWriter(OutputStream  outputStream , boolean flushOnNewline) Here, outputStream is an object of type OutputStream. flushOnNewLine  controls whether Java flushes the output stream  every time a  println( )  method is called.  If  flushOnNewLine  is  true   flushing automatically takes place. If  flushOnNewLine   is  false , flushing is not automatic.
Console Output using Character Streams To write to the console (monitor) using a  PrintWriter , specify  System.out  for the output stream and flush the stream after each call to println( ).  For example, the following line of code creates a  PrintWriter  that is connected to console (monitor) output. PrintWriter  pw = new PrintWriter(System.out, true); The Java program on the next slide demonstrates a PrintWriter  
Console Output using Character Streams // Demonstrate PrintWriter.  import java.io.*;  public class PrintWriterDemo {  public static void main(String[ ] args) {  PrintWriter pw = new PrintWriter(System.out, true);  int i = 120;  double d = 123.67;
Console Output using Character Streams pw.println(&quot;Using a PrintWriter.&quot;);  // PrintWriter Demo pw.println(i);  pw.println(d);  pw.println(i + &quot; + &quot; + d + &quot; is &quot; +  i +d);  }  // End of main( ) method }  // End of class PrintWriterDemo The output from the previous program is: Using a PrintWriter. 120 123.67 120 + 123.67 is  243.67
File Input & Output using Character Streams In general, to perform  character-based  file I/O, you will use the  FileReader   and  FileWriter  classes. Using a FileWriter FileWriter creates a Writer that you can use to write to a file. FileWriter is derived from OutputStreamWriter and Writer classes Commonly used constructors are: FileWriter (String  fileName)  throws IOException FileWriter (String  fileName, boolean  append ) throws IOException fileName  is the full path name of the file. If  append  is true, then output is appended to the end of the file.  Otherwise, the file is overwritten.
File I / O using Character Streams  FileWriter // A simple keyboard-to-disk utility that  demonstrates a FileWriter.  import java.io.*;  public class KtoD {  public static void main(String[ ]  args)  throws IOException {  String str;  FileWriter fw;  BufferedReader br =  new BufferedReader(  new InputStreamReader(System.in));
File I / O using Character Streams  FileWriter try {  fw = new FileWriter(&quot;test.txt&quot;);  // Try to open the file }  catch(IOException exc) {  System.out.println(“Error: “ + exc.getMessage( ) ); System.out.println(&quot;Cannot open output file.&quot;);  return ;  }
File I / O using Character Streams  FileWriter System.out.println(&quot;Enter text ('stop' to quit).&quot;);  do {  System.out.print(&quot;: &quot;);  str = br.readLine( );  if(str.compareTo(&quot;stop&quot;) == 0) break;  str = str + &quot;\r\n&quot;; // add carriage return  & newline  fw.write(str);  } while(str.compareTo(&quot;stop&quot;) != 0);  fw.close( );  }  // End of main ( )  method } // End of class KtoD
File I / O using Character Streams  FileReader The FileReader class creates a  Reader  that you can use to read the  contents of a file.  FileReader is derived from the InputStreamReader and Reader classes. It has access to the methods in those classes. The most common constructor is: FileReader(String  fileName )  throws FileNotFoundException where  fileName  is the  full path name  of  the file.  It throws a FileNotFoundException if the file does not exist.
File I / O using Character Streams  FileReader The following program reads a text file called  “test.txt” and displays the information on the screen. // A simple disk-to-screen utilitiy that  demonstrates a FileReader.  import java.io.*;  class DtoS {  public static void main(String[ ] args) throws Exception {  FileReader fr = new FileReader(&quot;test.txt&quot;);  BufferedReader br = new BufferedReader(fr);  String s;
File I / O using Character Streams  FileReader while((s = br.readLine()) != null)  {  System.out.println(s);  }  fr.close( );  // Close the file }  // End of main( ) method }  // End of DtoS class
The File Class: Objectives To discover file properties, delete and rename files using the  File  class  To understand how I/O is processed in Java  To distinguish between text I/O and binary I/O  To read and write characters using  FileReader  and  FileWriter   To improve the performance of text I/O using  BufferedReader  and  BufferedWriter   To write primitive values, strings, and objects as text using  PrintWriter  and  PrintStream   To read and write bytes using  FileInputStream  and  FileOutputStream  To read and write primitive values and strings using  DataInputStream / DataOutputStream   To store and restore objects using  ObjectOutputStream  and  ObjectInputStream , and to understand how objects are serialized and what kind of objects can be serialized  To use  RandomAccessFile  for both read and write.
The File Class The  File  class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string.  The  File  class is a wrapper class for the file name and its directory path.
Obtaining file properties and manipulating file
Example  Using the File Class  TestFileClass.java Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. Figure 1 shows a sample run of the program on Windows, and Figure 2 a sample run on Unix  (Windows) (Unix)
The File Class and Processing External Files The  File class  provides an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. You can create a new  File object  using the following statement: File  myfile  = new File (“myfile.dat”); You can use the File class to check properties of files, such as whether the file  exists , or is  readable , or  updateable .
The File Class and Processing External Files You can use the  getName( )  method to get the name of the file. For example, if (myfile.exists( ) ) System.out.println(“File “ + myfile.getName( ) + “ already exists”); The following statement creates a file using the full path using the Windows operating system: File myfile = new File(“C:\\Java\\myfile.data”);
The File Class and Processing External Files You can use the  getPath( )  method to get the full path of the file and the getParent( ) method to get the directory that contains the file. For example, if  (myfile.exists( ) ) { System.out.println(“The full path is  “ + myfile.getPath( ) ); System.out.println(“The directory is “ + myfile.getParent( ) ); }
Demo Program:  TestFileClass.java // TestFileClass.java: Demonstrate the File class  Chapt 18 I/O  ITP120 import java.io.*; import java.util.*; public class TestFileClass { public static void main(String[] args) { // Create a File object  File file = new File(&quot;.&quot;, &quot;images&quot; + File.separator + &quot;bill_gates.gif&quot;); System.out.println(&quot;Does it exist? &quot; + file.exists()); System.out.println(&quot;Can it be read? &quot; + file.canRead()); System.out.println(&quot;Can it be written? &quot; + file.canRead()); System.out.println(&quot;Is it a directory? &quot; + file.isDirectory()); System.out.println(&quot;Is it a file? &quot; + file.isFile()); System.out.println(&quot;Is it absolute? &quot; + file.isAbsolute()); System.out.println(&quot;Is it hidden? &quot; + file.isHidden()); System.out.println(&quot;What is its absolute path? &quot; +  file.getAbsolutePath());
Demo Program:  TestFileClass.java try { System.out.println(&quot;What is its canonical path? &quot; +  file.getCanonicalPath()); } catch (IOException ex) { } System.out.println(&quot;What is its name? &quot; + file.getName()); System.out.println(&quot;What is its path? &quot; + file.getPath()); System.out.println(&quot;When was it last modified? &quot; +  new Date(file.lastModified())); System.out.println(&quot;What is the path separator? &quot; +  File.pathSeparatorChar); System.out.println(&quot;What is the name separator? &quot; +  File.separatorChar); } }
Processing External Files Again, you must use  file streams  to read from or write to a disk file.  Once again, you can use  FileInputStream  or  FileOutputStream  for  byte  streams.  And you can use  FileReader  or  FileWriter  for  character  streams.
File I/O Stream Constructors To create a file stream, use these constructors: public FileInputStream (String  filenameString)  // Byte stream constructors public FileInputStream (File  file) public FileOutputStream (String  filenameString)  // Byte stream constructor public FileOutputStream (File  file) public FileReader (String  filenameString)  // Character stream constructors public FileReader (File  file) public FileWriter (String  filenameString)  // Character stream constructor public FileWriter (File  file)
File I/O Stream Constructors Constructing instances of  FileInputStream ,  FileOutputStream ,  FileReader , and  FileWriter  from file names: FileInputStream infile = new FileInputStream(&quot;in.dat&quot;); FileOutputStream outfile = new FileOutputStream(&quot;out.dat&quot;); FileReader infile = new FileReader(&quot;in.dat&quot;); FileWriter outfile = new FileWriter(&quot;out.dat&quot;);
Demo Program:  TestFileReader.java // TestFileReader.java  Chapter 18  I/O  ITP 120 import java.io.*; public class TestFileReader { public static void main(String[ ] args)  { FileReader input = null; try { // Create an input stream input = new FileReader(&quot;temp.txt&quot;); int code; // Repeatedly read a character and display it on the console while ((code = input.read()) != -1) System.out.print((char)code); }  // End of try block
Demo Program:  TestFileReader.java System.out.println(&quot;File temp.txt does not exist&quot;); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } } }  // End of class TestFileReader
Demo Program: TestFileWriter.java // TestFileWriter.java  Chapter 18  File I/O  ITP 120 import java.io.*; public class TestFileWriter { public static void main(String[ ] args) throws IOException { // Create an output stream to the file FileWriter output = new FileWriter(&quot;temp.txt&quot;, true); // Output a string to the file output.write(“ NVCC Introduction to Java Programming ITP 120 !!!&quot;); // Close the stream output.close(); } }
Processing External Files
Processing External Files The previous diagram shows that: FileInputStream, fis, is used to read data (bytes) from a file FileOutputStream, fos,  is used to write data (bytes)  to  a file Command line: java  CopyFileUsingByteStream  f1.txt  f2.txt See the Java program  CopyFileUsingByteStream  on the following slides  
Processing External Files  // CopyFileUsingByteStream.java  For  Copying  files  (byte streams) import java.io.*; public class CopyFileUsingByteStream { // Main method: args[0] for sourcefile and args[1] for target file public static void main(String[ ] args) {  // Declare input and output file streams FileInputStream fis = null; FileOutputStream fos = null;
Processing External Files  if (args.length !=2)  // args[0] is source file {    // args[1]  is target file System.out.println( &quot;Usage: java CopyFileUsingByteStream  f1  f2&quot;); System.exit(0);  // Stop the program }
Processing External Files  try {  // Create file input stream fis = new FileInputStream(new File(args[0])); // Create file output stream if the file does not exist File outFile = new File(args[1]); if (outFile.exists()) { System.out.println(&quot;file &quot; + args[1] + &quot; already exists&quot;); return; }
Processing External Files else fos = new FileOutputStream(args[1]);  // FileOutputStream // Display the file size System.out.println(&quot;The file &quot; + args[0] + &quot; has &quot;+ fis.available() + &quot; bytes&quot;);
Processing External Files  // Continuously read a byte from fis and write it to fos int r; while ((r = fis.read()) != -1)  // EOF is  -1  fos.write((byte)r); } catch (FileNotFoundException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;File not found: &quot; + args[0]); }
Processing External Files catch (IOException ex) { System.out.println(“Some IO Exception occurred”); System.out.println(“Error: “ + ex.getMessage( )); } Continues to next slide  
Processing External Files finally { try { if (fis != null) fis.close();  // Close the input & output files if (fos != null) fos.close(); } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); } }  // End of finally block }  //  End of main method }  // End of class CopyFileUsingByteStream
Filter Streams Filter streams  are streams that filter bytes or characters for some purpose. If you want to read  integers ,  doubles , or  Strings , you need a  filter class  to wrap the input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters . Use  FilterInputStream  and  FilterOutputStream  when you need to process  primitive numeric  types.
Filter Streams To process  strings ,  use  BufferedReader  and  PushbackReader  to filter characters. Note:  FilterInputStream  and  FilterOutputStream  are  abstract  classes.
FilterInputStream  subclasses DataInputStream   handles  binary  formats for all primitive data types. BufferedInputStream   gets data from the buffer and then reads them from the stream if necessary. LineNumberInputStream   keeps track of how many lines are read. PushBackInputStream   allows single-byte look-a-head.  Looks at a byte and pushes it back to the stream if the byte read is NOT the desired byte.
FilterOutputStream  subclasses DataOutputStream   outputs the  binary  formats for all primitive data types which is  useful if another program uses the output . BufferedOutputStream   outputs to the buffer first and then to the stream if necessary.  You may also call the  flush( )  method to write the buffer to the stream. PrintStream   outputs the  Unicode format  of all primitive types which is useful if the format is  output to the console .
Data Streams  (bytes) The data streams ( DataInputStream  and  DataOutputStream ) read and write Java primitive types in a  machine-independent   fashion. This enables you to write a data file for one computer  and read it on another computer that has a different operating system or file structure.
DataInputStream Methods defined in the DataInput Interface int readByte() throws IOException int readShort() throws IOException int readInt() throws IOException int readLong() throws IOException float readFloat() throws IOException double readDouble() throws IOException char readChar() throws IOException boolean readBoolean() throws IOException String readUTF() throws IOException
DataOutputStream Methods   defined in the DataOutput   interface   void writeByte(byte b) throws IOException  void writeShort(short is) throws IOException  void writeInt(int i) throws IOException  void writeLong(long l) throws IOException  void writeFloat(float f) throws IOException  void writeDouble(double d) throws IOException  void writeChar(char c) throws IOException  void writeBoolean(boolean b) throws IOException void writeBytes(String s) throws IOException void writeChars(String s) throws IOException void writeUTF(String s) throws IOException
DataInputStream & DataOutput Stream  Constructors Data streams are used as wrappers on existing input and output streams to filter data in the original stream. DataInputStream infile = new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); The above creates an input file for in.dat. DataOutputStream outfile = new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); The above creates an output file for out.dat.
Using Data Streams  The next  example shows a program that: Creates 10 random integers,  Stores them in a data file, Retrieves data from the file,  Displays the integers on the console.   See next slide  
Using Data Streams  Demo  Example  // TestDataStreams.java: Create a file, store it in binary form, and // display the contents of the file on the console import java.io.*; public class TestDataStreams { // Main method public static void main(String[ ] args) { // Declare data input and output streams DataInputStream dis = null; DataOutputStream dos = null;
Using Data Streams  Demo  Example  // Construct a temp file File tempFile = new File(&quot;mytemp.dat&quot;); // Check if the temp file exists if (tempFile.exists()) { System.out.println(&quot;The file mytemp.dat already exists,&quot; +&quot; delete it, rerun the program&quot;); System.exit(0); }
Using Data Streams  Demo Example // Write data try { // Create data output stream for tempFile dos = new DataOutputStream(new FileOutputStream(tempFile)); for (int i=0; i<10; i++) dos.writeInt((int)(Math.random()*1000)); }
Using Data Streams  Demo  Example  catch (IOException ex) { System.out.println(ex.getMessage( ) ); } finally { try { if (dos != null) dos.close( );  //  Close the file(s) } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) );  }
Using Data Streams  Demo  Example  // Read data try { // Create data input stream dis = new DataInputStream(new FileInputStream(tempFile)); for (int i=0; i<10; i++) System.out.print(&quot;  &quot;+dis.readInt ( ) );  // Display the integers }
Using Data Streams  catch (FileNotFoundException ex) { System.out.println(&quot;File not found“ + ex.getMessage( ) );); } catch (IOException ex) { System.out.println(ex.getMessage()); }
Using Data Streams  finally { try { if (dis != null)  dis.close( );  // Close the file(s) } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) )); } }  // End of finally block }  // End of main method }  // End of class  TestDataStreams
Using Data Streams  Demo  Example  The previous Java program  TestDataStreams.java  creates a  DataInputStream  object named  “dis” wrapped on  FileInputStream  and creates a  DataOutputStream  object  “dos” wrapped on  FileOutputStream Conceptually, Program   DataInputStream  dis  <-- fileInputStream <--mytemp.dat    DataOutputStream  dos    fileOutputStream    mytemp.dat The program uses a temporary file,  mytemp.dat , to store data. The program creates  mytemp.dat  if it does not exist and writes 10 random  integers into mytemp.dat.  The data in  mytemp.dat  is in binary format.
Character Classes  The classes that handle characters have at the top of their hierarchy,  Reader  and  Writer The subclasses branch out to provide specialized functionality. FileReader  provides functionality for reading streams of characters from files. BufferedReader  buffers character streams for efficiency FileWriter  for writing character streams to files. PrintWriter  for writing character streams.
File Class File class provides functionality for working directly with files in the operating system The File class provides  overloaded  constructors for creating File objects.  A File object can be created by giving the name of the file: File  inputFile = new File(“in.dat”);  // Same directory File  myInputFile = new File(“C:\\myDirectory\\in.dat”);  A File Object can refer to either a file or directory File theDir = new File(“C:\\myDir”);  //File object theDir refers to a directory Some File class methods: exists() that tests if the named file already exist. mkdir( String st ) for creating directories list()  for listing the contents of directories getPath()  gets the path of the named file length()  returns the file size in bytes
File Class Example:  DirectoryContents.java  listing the contents of a directory using File class import java.io.*; public class DirectoryContents {   public static void main(String[ ] args) { File myDir = new File(“C:\\&quot;); if(myDir.isDirectory( ) )  { System.out.println(&quot;Contents of directory &quot; + myDir ); String[ ] contents = myDir.list();   for( int I = 0; I < contents.length; I++) System.out.println(contents[ I ]  ); }  // End of “if” block }  // End of main method }  // End of class DirectoryContents
Using Java I/O Many of the methods including constructors of Java.io classes throw exceptions:  The most commonly thrown is IOException. Reading data from the keyboard BufferedReader in  = new BufferedReader(new InputStreamReader(System.in); An InputStreamReader is like an adapter, it reads byte streams and converts it into character streams BufferedReader wraps the InputStreamReader to provide extra functionality, allowing to buffer the input to support  readLine()
Using Java I/O Example  Reading strings from the keyboard Import java.io.* public class ReadStringFromKeyboard { public static void main(String[ ]  args) { // Converts from bytes to characters BufferedReader in = new BufferedReader(new InputStreamReader (System.in)); String yourInput;  try { System.out.println(&quot;Please enter any string and hit the return key when done:&quot;); yourInput = in.readLine( ); System.out.println(&quot;\nBelow is the input you entered&quot;); System.out.println(yourInput); } catch (IOException ex) { System.out.println(“Could not read from the keyboard” } }  // End of main method }  // End of class ReadStringFromKeyboard
Using Java I/O Example:  Reading from an external file public class ReadFromFile { public static void main(String[ ]  args) {   String st = null; File  inputFileName = null; FileReader  inputFile = null; BufferedReader  in = null; try {   inputFileName = new File(&quot;Input1.txt&quot;);   inputFile = new FileReader(inputFileName); in = new BufferedReader(inputFile);   /* Note:  The above 3 lines can be combined in one line as below in = new BufferedReader(new FileReader(new File(&quot;Input1.txt&quot;)));  */
Using Java I/O Example  Continued // Now let us start reading from the opened file while((st = br.readLine()) != null )   {   System.out.println(st);  // Print the string }   } catch (FileNotFoundException fnex) {  System.out.println(“Error: “ + fnex.getMessage( ) ); System.out.println(&quot;Input file was not found&quot;); }   catch (IOException ex) {  System.out.println(“Error: “ + ex.getMessage( ) );   System.out.println(&quot;There was a problem reading from the file&quot;); }
Using Java I/O Example  continued finally { if( br  != null) try { br.close( );  // Close the file } catch (Exception ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;There was a problem with closing the file&quot;); } }  // End finally block }  // End of main method }  // End of class
Print Streams The data output stream outputs a  binary representation  of data, so you cannot view its contents as text. In Java, you can use print streams to output data into files. These files can then be viewed as text. The  PrintStream  and  PrintWriter  classes provide the functionality for doing this. PrintStream is for  bytes PrintWriter is for  characters  (Unicode)
Print Streams:   PrintWriter  Constructors PrintWriter(Writer out) PrintWriter(Writer out, boolean autoFlush) PrintWriter(OutputStream out) PrintWriter(OutputStream out, boolean autoFlush)
Print Streams:  PrintWriter   Methods  (for chars) void print(Object o) void print(String s) void println(String s) void print(char c) void print(char[] cArray) void print(int i) void print(long l) void print(float f) void print(double d) void print(boolean b)
Print Streams:  PrintWriter  Methods Note: On the previous slide, you may replace  print  with  println  in the various method definitions. The  println  method, which prints the object, is followed by a new line.  When the object is passed to  print  or  println ,  the object’s  toString( )  method converts it to a String object.
Demo Program Example Using Print Streams The next sample Java program creates a print stream,  pw , of  PrintWriter , wrapped on  FileOutputStream , for text format. pw = new PrintWriter(new FileOutputStream(tempFile),true); The program creates the file, arg[0], if that file does not already exist. The program writes 10 random integers into the file by using the data output stream, then closes the stream. The data file could be viewed by using the  type   command in DOS
Using Print Streams:  Demo  Example  // TestPrintWriters.java: Create a text file // using PrintWriter import java.io.*;   public class TestPrintWriters { // Main method: args[0] is the output file public static void main(String[] args) { // Declare print stream PrintWriter pw = null;  
Using Print Streams:  Demo example  // Check usage if (args.length != 1) { System.out.println(&quot;Usage: java  TestPrintWriters file&quot;); System.exit(0); }   File tempFile = new File(args[0]);  
Using Print Streams:  Demo Example  if (tempFile.exists()) { System.out.println(&quot;The file &quot; + args[0] + &quot; already exists, delete it, rerun the program&quot;); System.exit(0); }
Using Print Streams:  Demo Example  // Write data try { // Create print writer stream for tempFile pw = new PrintWriter(new FileOutputStream(tempFile), true); for (int i=0; i<10; i++) pw.print(&quot; &quot;+(int)(Math.random()*1000)); }
Using Print Streams:  Demo Example  catch (IOException ex) { System.out.println(ex.getMessage()); } finally { // Close files if (pw != null) pw.close(); } } }
Using Print Streams:  Demo Example  C:\test>java TestPrintWriters Usage:  java TestPrintWriters  filename C:\test>java TestPrintWriters  test.dat C:\test>type  test.dat  (Use  the TYPE  command to see data in file) 567  915  7  23  677  455  402  997  290  549
Print Streams
Using Java I/O Example:  WriteToFile.java  Writing text to external files import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class WriteToFile { public WriteToFile( )  {  }  // Empty constructor
Using Java I/O Example:  WriteToFile.java  (continued) public static void main (String[ ]  args) { File  outputFileName = null; PrintWriter  outToFile = null; try { outputFileName = new File(&quot;outFile1.txt&quot;); outToFile = new PrintWriter( new FileWriter(outputFileName)); // Now we can start writing to file outToFile.println(&quot;This message is going to the output file&quot;); outToFile.println(&quot;This will be line two in the output file&quot;); outToFile.println(&quot;We can write the output file any time we want&quot;); outToFile.flush( );  // Flush output file }
Using Java I/O Example 18.6 catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;There was a problem writing to the output file&quot;); } finally { if ( outToFile != null ) outToFile.close( );  // Close output file }  // End of finally block }  // End of main method }  // End of class  WriteToFile
Buffered Streams in Java Java introduces buffered streams that speed up input and output by reducing the number of reads and writes.  In the case of input, a bunch of data is  read all at once  instead of one byte at a time.  In the case of output, data are first cached into a buffer, then written all together to the file.  Using buffered streams is highly recommended.
Buffered Stream Constructors BufferedInputStream (InputStream in)  BufferedInputStream (InputStream in, int bufferSize)  BufferedOutputStream (OutputStream in)  BufferedOutputStream (OutputStream in, int bufferSize) BufferedReader(Reader in) BufferedReader(Reader in, int bufferSize) BufferedWriter(Writer out) BufferedWriter(Writer out, int bufferSize)
Demo Program:  ViewFile.java  (A Text Viewer program) This case study writes a program that views a text file in a text area. The user enters a filename in a text field and clicks the View button; the file is then displayed in a text area.
Buffered Streams in Java  ViewFile program // ViewFile.java: Read a text file and store it in a text area import java.awt.*;  //  Buffered I/O  example  (Demo program) import java.awt.event.*; import java.io.*; import javax.swing.*; public class ViewFile extends MyFrameWithExitHandling implements ActionListener { // Button to view view private JButton jbtView = new JButton(&quot;View&quot;);
Buffered Streams in Java  ViewFile program // Text field to receive file name private JTextField jtf = new JTextField(12); // Text area to display file private JTextArea jta = new JTextArea(); public static void main(String [ ]  args) // Main method { ViewFile frame = new ViewFile(); frame.setTitle(&quot;View File Program in Java&quot;); frame.setSize(400, 300); frame.setVisible(true); }
Buffered Streams in Java  ViewFile program // Constructor public ViewFile() { // Panel p to hold a label, a text field, and a button Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Label(&quot;Filename&quot;), BorderLayout.WEST); p.add(jtf, BorderLayout.CENTER); jtf.setBackground(Color.yellow); jtf.setForeground(Color.red); p.add(jbtView, BorderLayout.EAST);
Buffered Streams in Java  ViewFile program // Add jtaFile to a scroll pane JScrollPane jsp = new JScrollPane(jtaFile); // Add jsp and p to the frame getContentPane().add(jsp, BorderLayout.CENTER); getContentPane().add(p, BorderLayout.SOUTH); // Register listener jbtView.addActionListener(this); }
Buffered Streams in Java  ViewFile program // Handle the &quot;View&quot; button public void actionPerformed(ActionEvent e) { if (e.getSource() == jbtView) showFile(); }
Buffered Streams in Java  ViewFile program // Display the file in the text area private void showFile() { // Use a BufferedStream to read text from the file BufferedReader infile = null; // Get file name from the input text field at the bottom String filename = jtf.getText().trim(); String inLine;
Buffered Streams in Java  ViewFile program try { // Create a buffered stream infile = new BufferedReader(new FileReader(filename)); // Read a line inLine = infile.readLine(); boolean firstLine = true;
Buffered Streams in Java  ViewFile program while (inLine != null) // Append the line to the text area { if (firstLine)  { firstLine = false; jtaFile.append(inLine);  } else { jta.append(&quot;\n&quot; + inLine);  } inLine = infile.readLine(); } }  // End of try block
Buffered Streams in Java  ViewFile program catch (FileNotFoundException ex) {  System.out.println(“Error: “ +  ex.getMessage( ) ); System.out.println(&quot;File not found: &quot; + filename); } catch (IOException ex) { System.out.println(ex.getMessage()); }
Buffered Streams in Java  ViewFile program finally { try { if (infile != null)  infile.close( );  // Close input file } catch (IOException ex) { System.out.println(“Error: “ +  ex.getMessage( )); } }  // End of finally block }  // End of method showFile() }  // End of class ViewFile
Buffered Streams in Java  ViewFile program Demostrate the ViewFile program by running: java  ViewFile  (at the command prompt) Wait for Java window to appear. then type  Comcast1.txt or the name of some text file in the text box at the bottom of the Java window. Look at the contents on the text file in the Java window.
Text Input & Output on the Console In previous chapters, you used text input and output with the  System  class. The System class, as you have already seen, contains 3 I/O objects:  System.in, System.out, and System.err .  The objects  in, out  and  err   are static variables.  The variable  in  is of  InputStream  type and  out , err  are of  PrintStream  type.  (byte streams) These are the basic objects that all java programmers use to get input from the keyboard, send output to the screen, and display error messages.
Text Input & Output on the Console To perform console output, you can use any of the methods for  PrintStream  in the  System.out object. To get input from the keyboard, you can use the following statements to read a string from the keyboard  See next slide        AND ALSO VIEW THE EXPANDED VERSION of  MyInput.java  which follows thereafter
Text Input & Output on the Console BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1); // Note:  the  1  above means a buffer size of 1 // Declare and initialize the string  String string = &quot; &quot;; // Get the string from the keyboard try {  string = br.readLine();  } catch (IOException ex)  { System.out.println(ex);  }
Text I/O on the Console  MyInput.java  (full) public class MyInput  // Expanded version {  // Read a string from the keyboard public static String readString() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1); // Declare and initialize the string String string = &quot; &quot;; // Get the string from the keyboard try  { string = br.readLine();  } catch (IOException ex)  { System.out.println(ex) ;  }
Text I/O on the Console  MyInput.java  (full) // Return the string obtained from the keyboard return string; } // Read an int value from the keyboard public static int readInt() { return Integer.parseInt(readString()); }
Text I/O on the Console  MyInput.java  (full) // Read a double value from the keyboard public static double readDouble() { return Double.parseDouble(readString()); } // Read a byte value from the keyboard public static double readByte() { return Byte.parseByte(readString()); }
Text I/O on the Console  MyInput.java  (full) // Read a short value from the keyboard public static double readShort() { return Short.parseShort(readString()); } // Read a long value from the keyboard public static double readLong() { return Long.parseLong(readString()); }
Text I/O on the Console  MyInput.java  (full) // Read a float value from the keyboard public static double readFloat() { return Float.parseFloat(readString()); } }
Random Access Files  (byte streams) Java allows you to access the contents of a file in  random order To do this, you will use  RandomAccessFile  which encapsulates a random-access file. RandomAccessFile  is  a stream  class  derived from Object RandomAccessFile is NOT derived from InputStream or OutputStream. RandomAccessFile implements  interfaces  InputData &  OutputData InputData &  OutputData define the basic I/O methods. You can also  position the file pointer  within the file using the method  seek ( )
Random Access Files  (Constructor(s)) The constructor for RandomAccessFile is: RandomAccessFile (String  filename , String  access ) throws FileNotFoundException The name of the file is passed in  filename The term  access  determines what type of file access is permitted. If  the access is  “r”, the file is  read-only. If the  access is “rw”, the file is opened in  read-write  mode.
Random Access Files (Methods) The method  seek ( )   is used to set the current position of the file pointer within a random access file:   void  seek (long  newpos )  throws IOException newpos  specifies the new position, in  bytes , of the file pointer from  the beginning of the file.  After a call to  seek( ),  the next read or write operation will occur at the  new file position.
Random Access Files  (Methods) public long getFilePointer ( ) throws IOException Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. public long length ( ) throws IOException Returns the length of the file in bytes. public final void writeChar (int  v) throws IOException Writes a character to the file as a 2-byte Unicode character with the higher byte written first. public final void writeChars(String s) throws IOException Writes a string to a file as a sequence of characters.
Random Access Files RandomAccessFile  implements the  read ( )  and  write ( )  methods. It also implements the  InputData  and  OutputData  interfaces , which means that methods to read and write the simple data types such as  readInt( )  and  writeDouble( )  are available. The slides which follow show a Java program that demonstrates random  access file  I/O.  The program writes 6 double numbers to a file and then reads  them back in a non-sequential order.
Random Access Files // Demonstrate random access files  RandonAccessDemo.java import java.io.*;  public class RandomAccessDemo {  public static void main(String[ ]  args)  throws IOException {  double data[ ] = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 };  double d;  RandomAccessFile raf;
Random Access Files try {  raf = new RandomAccessFile(&quot;random.dat&quot;, &quot;rw&quot;);  }  catch(FileNotFoundException ex)  {  System.out.println(&quot;Cannot open file.&quot;);  System.out.println(“Error: “ + ex.getMessage( ) ); return ;  }
Random Access Files // Write values to the file.  for (int i=0; i < data.length; i++) {  try {  raf.writeDouble(data[i]);  }  catch(IOException ex) {  System.out.println(“Error: “ + ex.getMessage( )); System.out.println(&quot;Error writing to file.&quot;);  return ;  } }  // End of  “for” loop
Random Access Files try {  // Now, read back specific values  raf.seek(0); // seek to first double  d = raf.readDouble();  System.out.println(&quot;First value is &quot; + d);  raf.seek(8); // seek to second double  d = raf.readDouble();  System.out.println(&quot;Second value is &quot; + d);  raf.seek(8 * 3); // seek to fourth double  d = raf.readDouble();  System.out.println(&quot;Fourth value is &quot; + d);  System.out.println();
Random Access Files // Now, read every other value.  System.out.println(&quot;Here is every other value: &quot;);  for (int i=0; i < data.length; i+=2) {  raf.seek(8 * i); // seek to ith double  d = raf.readDouble();  System.out.print(d + &quot; &quot;);  }  // End of  “for” loop }  // End of try block
Random Access Files catch(IOException exc)  {  System.out.println(“Error: “ + exc.getMessage( ) ); System.out.println(&quot;Error seeking or reading.&quot;);  } raf.close( );  // Close the file }  // End of main ( ) }  // End of class RandomAccessDemo
Random Access Files Output from the previous Java program RandomAccessDemo: First value is  19.4 Second value is  10.1 Fourth value is 33.0 Here is every other value: 19.4  123.54  87.9
Case Studies: Address Book Now let us use  RandomAccessFile  to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The  Add  button stores a new address to the end of the file. The  First ,  Next ,  Previous , and  Last  buttons retrieve the first, next, previous, and last addresses from the file, respectively.
Parsing Text Files  The  StreamTokenizer  class lets you take an input stream and parse it into words, which are known as  tokens .  The tokens are read one at a time. The following is the  StreamTokenizer  constructor: StreamTokenizer st =   StreamTokenizer(Reader is)
StreamTokenizer   Constants TT_WORD The token is a word. TT_NUMBER The token is a number. TT_EOL The  end of the line  has been read. TT_EOF The  end of the file  has been read.
StreamTokenizer  Variables int ttype  (token type) Contains the current token type, which matches one of the constants listed on the preceding slide. double nval  Contains the value of the current token if that token is a number. String sval Contains a string that gives the characters of the current token if that token is a word.
StreamTokenizer   Methods public int nextToken() throws  IOException Parses the next token from the input stream of this  StreamTokenizer . The type of the next token is returned in the  ttype field. If  ttype == TT_WORD , the token is stored  in  sval ;  if  ttype == TT_NUMBER , the  token is stored in  nval .
Example : Demo program  Using  StreamTokenizer  Demo:  ParsingTextFile.java
ParsingTextFile.java  (Demo program) // ParsingTextFile.java:  ITP 120 // Process text file using StreamTokenizer  Chapter 18  I/O import java.io.*; public class ParsingTextFile { // Main method public static void main(String[] args) { // Declare file reader and writer character (2 bytes) streams FileReader frs = null; FileWriter fws = null; // Declare streamTokenizer StreamTokenizer in = null;
ParsingTextFile.java  (Demo) // Declare a print stream PrintWriter out = null; // For input file fields: student name, midterm1, // midterm2, and final exam score String sname = null; double midterm1 = 0; double midterm2 = 0; double finalScore = 0; // Computed total score double total = 0; try { // Create file input and output streams frs = new FileReader(&quot;grades.dat&quot;); fws = new FileWriter(&quot;gradesout.dat&quot;);
ParsingTextFile.java  (Demo) // Create a stream tokenizer wrapping file input stream in = new StreamTokenizer(frs); out = new PrintWriter(fws);  // Create PrintWriter object // Read first token in.nextToken(); // Process a record  //  TTs are Tokenizer constants while (in.ttype != in.TT_EOF)  //  TT_EOF means end of file { // Get student name if (in.ttype == in.TT_WORD)  // TT_WORD means token is a word sname = in.sval; else System.out.println(&quot;Bad file format&quot;);
ParsingTextFile.java  (Demo) // Get midterm1 if (in.nextToken() == in.TT_NUMBER) //TT_NUMBER means token is a number midterm1 = in.nval; else System.out.println(&quot;Bad file format&quot;); // Get midterm2 score if (in.nextToken() == in.TT_NUMBER) midterm2 = in.nval; else System.out.println(&quot;Bad file format&quot;); // Get final  exam score if (in.nextToken() == in.TT_NUMBER) finalScore = in.nval;
ParsingTextFile.java  (Demo) total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4; out.println(sname + &quot;  &quot; + total); in.nextToken( ); } } catch (FileNotFoundException ex) { System.out.println(&quot;Error: &quot; + ex.getMessage()); System.out.println(&quot;File not found: in.dat&quot;); } catch (IOException ex) { System.out.println(ex.getMessage()); }
ParsingTextFile.java  (Demo) finally  // Always execute finally block { try { if (frs != null) frs.close(); if (fws != null) fws.close(); } catch (IOException ex) { System.out.println(ex); } } System.out.println(&quot;To view input file,  TYPE  GRADES.DAT&quot;); System.out.println(&quot;To view output file, TYPE  GRADESOUT.DAT&quot;); }  // End of main method }  // End of class
Chapter 18 Demo Programs ReadBytes.java WriteDemo.java ShowFile.java CopyFile.java  CopyFileUsingByteStream.java CompFile.java  RWData.java RandomAccessDemo.java PrintWriterDemo.java ReadChars.java ReadLines.java
Chapter 18 Demo Programs TestDataStreams.java TestFileClass.java TestPrintWriters.java ViewFile.java  (cute file viewer program) ParsingTextFile.java TestRandomAccessFile.java needs these class files: AddressBook.java FixedLengthStringIO.class
Chapter 18  Demo Programs TestDataStream.java TestFileClass.java TestFileReader.java TestFileStream.java TestFileWriter.java TestObjectStreamForArray.java TestObjectInputStream.java TestObjectOutputStream.java AddressBook.java  (with FixedLengthStringIO.java) Other created or required files:  object.dat, temp.txt, student.dat
End of Presentation
Ad

More Related Content

What's hot (20)

IO In Java
IO In JavaIO In Java
IO In Java
parag
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
cs19club
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
myrajendra
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
myrajendra
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
Nem Sothea
 
Files in java
Files in javaFiles in java
Files in java
Muthukumaran Subramanian
 
IO In Java
IO In JavaIO In Java
IO In Java
parag
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
myrajendra
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
myrajendra
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
Nem Sothea
 

Viewers also liked (20)

I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
Learn advanced java programming
Learn advanced java programmingLearn advanced java programming
Learn advanced java programming
TOPS Technologies
 
Java I/O
Java I/OJava I/O
Java I/O
Jussi Pohjolainen
 
2310 b 11
2310 b 112310 b 11
2310 b 11
Krazy Koder
 
Perl Development
Perl DevelopmentPerl Development
Perl Development
Mindfire Solutions
 
01 Ajax Intro
01 Ajax Intro01 Ajax Intro
01 Ajax Intro
Dennis Pipper
 
Nosql availability & integrity
Nosql availability & integrityNosql availability & integrity
Nosql availability & integrity
Fahri Firdausillah
 
Introduction To Silverlight and Prism
Introduction To Silverlight and PrismIntroduction To Silverlight and Prism
Introduction To Silverlight and Prism
tombeuckelaere
 
Java swing
Java swingJava swing
Java swing
profbnk
 
Forms authentication
Forms authenticationForms authentication
Forms authentication
SNJ Chaudhary
 
2310 b 09
2310 b 092310 b 09
2310 b 09
Krazy Koder
 
PyCologne
PyColognePyCologne
PyCologne
Andreas Schreiber
 
Oid structure
Oid structureOid structure
Oid structure
Remco Boksebeld
 
5 Key Components of Genrocket
5 Key Components of Genrocket5 Key Components of Genrocket
5 Key Components of Genrocket
GenRocket
 
Advance Java
Advance JavaAdvance Java
Advance Java
Vidyacenter
 
Ajax & ASP.NET 2
Ajax & ASP.NET 2Ajax & ASP.NET 2
Ajax & ASP.NET 2
Talal Alsubaie
 
Oracle 10g Application Server
Oracle 10g Application ServerOracle 10g Application Server
Oracle 10g Application Server
Mark J. Feldman
 
Java/Swing
Java/SwingJava/Swing
Java/Swing
Momentum Design Lab
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
Tomi Juhola
 
Csc153 chapter 02
Csc153 chapter 02Csc153 chapter 02
Csc153 chapter 02
PCC
 
Ad

Similar to Itp 120 Chapt 19 2009 Binary Input & Output (20)

Io Streams
Io StreamsIo Streams
Io Streams
phanleson
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
uthayashangar1
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
ssuser9d7049
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
siragezeynu
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
GayathriRHICETCSESTA
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
Io streams
Io streamsIo streams
Io streams
Elizabeth alexander
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
Rakesh Madugula
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
uthayashangar1
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
ssuser9d7049
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Ad

More from phanleson (20)

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
phanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
phanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
phanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
phanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
phanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
phanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
phanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
phanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
phanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
phanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
phanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
phanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
phanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
phanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
phanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
phanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
phanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
phanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
phanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
phanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
phanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
phanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
phanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
phanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
phanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
phanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
phanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
phanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
phanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
phanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
phanleson
 

Itp 120 Chapt 19 2009 Binary Input & Output

  • 1. Chapter 19 Binary Input & Output Java I ITP 120
  • 2. Chapter Objectives To understand how I/O is handled in Java To distinguish between text I/O and binary I/O To read and write bytes using FileInputStream and FileOutputStream To read and write primitive values and strings using the DataInputStream and DataOutputStream classes To store and restore objects using ObjectOutputStream and ObjectInputStream , and to understand how objects are serialized and what kind of objects can be serialized To use the Serializable interface to enable objects to be serializable (optional) To know how to serialize arrays (optional) To use RandomAccessFile for both read and write (Optional).
  • 3. Overview The java.io.* package provides a library of classes to read and write various types of data. In Java, all data I/O is handled in the form of streams Data streams can be byte streams or character streams The java.io package has classes that process byte streams of all types NOTE: In Java, a character is 2 BYTES ! Also NOTE: a Unicode character is 2 bytes ! The Reader and Writer classes process character streams. Streams can be layered, so that one type of streams can be converted to another type of streams by chaining . Chaining a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .
  • 4. Overview --- Streams A stream is an abstraction of a continuous one-way flow of data .
  • 5. 2 Types of Stream Classes: Bytes & Characters The stream classes can be categorized into two types: byte streams and character streams . The InputStream/OutputStream class is the root of all BYTE stream classes The Reader/Writer class is the root of all CHARACTER stream classes. The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer .
  • 6. Byte Stream Classes (note: the word “stream” )
  • 7. Character Stream Classes (Character = 2 bytes)
  • 8. How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. Formatter output = new Formatter(&quot;temp.txt&quot;); output.format(&quot;%s&quot;, &quot;Java 101&quot;); output.close(); Scanner input = new Scanner(new File(&quot;temp.txt&quot;)); System.out.println(input.nextLine());
  • 9. Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte -type value C7 in a binary file, because decimal 199 equals to hex C7 .
  • 10. Binary I/O Text I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
  • 12. The value returned is a byte as an int type. InputStream
  • 13. The value is a byte as an int type. OutputStream
  • 14. FileInputStream/FileOutputStream FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
  • 15. FileInputStream To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.
  • 16. FileOutputStream To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append)    If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter. TestFileStream Run
  • 17. FilterInputStream/FilterOutputStream Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes.
  • 18. DataInputStream/DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.
  • 19. DataInputStream DataInputStream extends FilterInputStream and implements the DataInput interface.
  • 20. DataOutputStream DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
  • 21. Characters and Strings in Binary I/O A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output. The writeChars(String s) method writes the Unicode for each character in the string s to the output. Why UTF-8? What is UTF-8? UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.
  • 22. Using DataInputStream / DataOutputStream Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream)   The statements given below create data streams. The first statement creates an input stream for file in.dat ; the second statement creates an output stream for file out.dat . DataInputStream infile = new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); DataOutputStream outfile = new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); TestDataStream Run
  • 23. Checking End of File TIP: If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file. Order and Format CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF , you must read names using readUTF .
  • 24. BufferedInputStream/ BufferedOutputStream Using buffers to speed up I/O BufferedInputStream / BufferedOutputStream does not contain new methods. All the methods BufferedInputStream / BufferedOutputStream are inherited from the InputStream / OutputStream classes.
  • 25. Constructing BufferedInputStream / BufferedOutputStream // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize)   // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize)
  • 26. Case Studies: Copy File This case study develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command: java Copy source target   The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists. Copy Run
  • 27. Object I/O DataInputStream / DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream / ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings. Optional
  • 28. ObjectInputStream ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants .
  • 29. ObjectOutputStream ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
  • 30. Using Object Streams You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in)   // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) TestObjectOutputStream Run TestObjectInputStream Run
  • 31. Random Access Files All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.
  • 33. File Pointer A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt() , the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.
  • 34. RandomAccessFile Methods Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream . For example, readInt() , readLong() , writeDouble() , readLine() , writeInt() , and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.
  • 35. RandomAccessFile Methods, cont. void seek(long pos) throws IOException; Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.
  • 36. RandomAccessFile Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first. final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.
  • 37. RandomAccessFile Constructor RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;rw&quot;); //allows read and write RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;r&quot;); //read only
  • 38. Case Studies: Address Book Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First , Next , Previous , and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively. Optional
  • 39. Fixed Length String I/O Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks. FixedLengthStringIO
  • 40. End of Presentation Binary Input & Output Chapter 18
  • 41. How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. Formatter output = new Formatter(“outfile.txt&quot;); output.format(&quot;%s&quot;, &quot;Java 120&quot;); // Write a string to outfile.txt output.close(); // Close the output file outfile.txt Scanner input = new Scanner(new File(&quot;temp.txt&quot;)); // Create object System.out.println(input.nextLine()); // Read a line
  • 42. Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte -type value C7 in a binary file ( Note: decimal 199 equals to Hex C7 .)
  • 43. Binary File I/O Text I/O requires encoding and decoding. The JVM converts a Unicode char to a file-specific encoding when writing a character and coverts a file-specific encoding to a Unicode char when reading a character. Binary I/O does not require conversions . When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
  • 44. Binary I/O Classes Inheritance Hierarchy
  • 45. The value returned is a byte as an int type. InputStream (a byte stream class)
  • 46. The value is a byte as an int type. OutputStream ( a byte stream class)
  • 47. FileInputStream & FileOutputStream (byte streams) FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
  • 48. FileInputStream (byte stream) To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.
  • 49. FileOutputStream (byte stream) To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append) // append = true to add on to the file    If the file does not exist , a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter. Demo Program: TestFileStream.java
  • 50. FilterInputStream/FilterOutputStream Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DataInputStream and DataOutputStream to filter bytes.
  • 51. DataInputStream & DataOutputStream (byte streams) DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and outputs the bytes to the stream.
  • 52. DataInputStream ( byte stream) DataInputStream extends FilterInputStream and implements the DataInput interface.
  • 53. DataOutputStream (byte stream) DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
  • 54. Characters and Strings in Binary I/O A Unicode char is 2 bytes. The writeChar(char ch) method writes the Unicode of character ch to the output. The writeChars(String str) method writes the Unicode for each character in the string str to the output file. What is UTF-8 ? Why use UTF-8 ? [ UTF means Unicode Text File ] UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) (127 decimal) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.
  • 55. Using DataInputStream / DataOutputStream Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream)   The statements below create data streams. The first statement creates an input stream for file in.dat ; the second statement creates an output stream for file out.dat . DataInputStream infile = new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); DataOutputStream outfile = new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); Demo Program: TestDataStream.java
  • 56. Checking for the End of File (EOF) TIP: If the program tried to read data at the end of a stream, an EOFException would occur. How do you check the end of a file? Use input.available() to check for EOF. if input.available() == 0 then the program is at the end of a file. (EOF) Order and Format CAUTION: You have to read the data in the same order and same format in which they are stored. For example, if names are written in UTF-8 using writeUTF (String str) , you MUST read the names using the readUTF method.
  • 57. BufferedInputStream/ BufferedOutputStream Use buffers to speed up I/O processes BufferedInputStream / BufferedOutputStream does not contain new methods. All the methods BufferedInputStream / BufferedOutputStream are inherited from the InputStream / OutputStream classes.
  • 58. Constructing BufferedInputStream / BufferedOutputStream // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize)   // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStream out, int bufferSize)
  • 59. CopyFile.java CopyFile.java is a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command: java CopyFile source target Also: java CompFile source target   The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists.
  • 60. Object I/O (optional) DataInputStream / DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream / ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.
  • 61. ObjectInputStream (optional) ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants .
  • 62. ObjectOutputStream (optional) ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
  • 63. Using Object Streams (optional) You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in)   // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) Demo: TestObjectOutputStream.java TestObjectInputStream.java
  • 64. The Serializable Interface Not all objects can be written to an output stream. Objects that CAN be written to an object stream is said to be serializable . A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement the Serializable interface. The Serializable interface is a marker interface . It has no methods, so you don't need to add additional code in your class that implements Serializable . Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.
  • 65. The transient Keyword If an object is an instance of Serializable , but it contains non-serializable instance data fields , can the object be serialized? The answer is NO ! To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.
  • 66. The transient Keyword, cont. Consider the following class:   public class ITP120 implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); } class A { } // A is not serializable   When an object of the ITP120 class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.
  • 67. Serializing Arrays (optional) An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject . Listing 18.6 stores an array of five int values, an array of three strings, and an array of two JButton objects, and reads them back to display on the console. Demo Program: TestObjectStreamForArray.java
  • 68. Random Access Files All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.
  • 70. File Pointers A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data . For example, if you read an int value using readInt() , the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.
  • 71. File Pointers (moving the pointer 4 bytes ahead)
  • 72. RandomAccessFile Methods Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream . For example, readInt() , readLong() , writeDouble() , readLine() , writeInt() , and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.
  • 73. RandomAccessFile Methods, cont. void seek(long pos) throws IOException; Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.
  • 74. RandomAccessFile Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first. final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.
  • 75. RandomAccessFile Constructors RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;rw&quot;); //allows read and write to the file RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;r&quot;); //read only Demo program: TestRandomAccessFile.java (uses FixedLengthStringIO.java)
  • 76. Case Study: Address Book Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First , Next , Previous , and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively. Run: AddressBook.java which uses FixedLengthStringIO.java
  • 77. Fixed Length String I/O Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks. FixedLengthStringIO
  • 78. Chapter 18 Demo Programs ReadBytes.java (skip) WriteData.java WriteDemo.java ReadData.java ShowFile.java CopyFile.java CopyFileUsingByteStream.java CompFile.java RWData.java RandomAccessDemo.java PrintWriterDemo.java ReadChars.java or BuffReader.java ReadLines.java (BufferedReader)
  • 79. Chapter 18 Demo Programs TextFileScannerDemo.java Uses input file morestuff.txt HasNextLineDemo.java Uses input file original.txt and creates output file numbered.txt BufferReaderDemo.java Uses input file: buffer.txt
  • 80. Chapter 18 Demo Programs TestDataStreams.java TestFileClass.java TestPrintWriters.java ViewFile.java (GUI text file viewer program) needs MyFrameWithExitHanding.java class file ParsingTextFile.java (needs grades.dat file) (creates gradesout.dat) TestRandomAccessFile.java AddressBook.java (creates file address.dat) needs FixedLengthStringIO.class file
  • 81. Chapter 18 Demo Programs TestDataStream.java TestFileReader.java (needs temp.txt) TestFileStream.java TestFileWriter.java (needs testdata.txt) TestObjectStreamForArray.java ( creates array.dat) TestObjectOutputStream.java (creates object.dat) TestObjectInputStream.java (reads object.dat)
  • 82. Chapter 18 Input / Output Optional: More on Java File I/O Chapter 18 Java I ITP 120
  • 83. Chapter 18: More on Input and Output Stream Classes (byte & character streams) Predefined Streams (System.in, System.out, System.err) Processing External Files Data Streams Print Streams Buffered Streams Text Input and Output on the Console Random Access Files
  • 84. Chapter 18 Input /Output Objectives Understand input & output streams and learn how to create them. Discover the uses of byte and character streams. To know how to read from / write to external files using file streams. To become familiar with the File class. To use print streams to output data of primitive types in text format. To know how to read and write text data files . Use text input and output on the console. Use RandomAccessFile for reading & writing random access files.
  • 85. Overview The java.io.* package provides a library of classes to read and write various types of data. In Java, all data I/O is handled in the form of streams Data streams can be byte streams or character streams The java.io package has classes that process byte streams of all types NOTE: In Java, a character is 2 BYTES ! NOTE: Unicode character is 2 bytes ! The Reader and Writer classes process character streams. Streams can be layered, so that one type of streams can be converted to another type of streams by chaining . Chaining a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .
  • 86. Overview Streams In Java, all Input/Output is handled by streams A stream is an abstraction of the continuous one-way flow of data Java streams can be applied to any source of data, so it is easy to get input from the keyboard and send output to a monitor, and the same applies to file input & output. All streams EXCEPT random-access file streams flow only in one direction. See the diagram on the next slide 
  • 87. Overview --- Streams A stream is an abstraction of a continuous one-way flow of data .
  • 88. Overview and Background The original version of Java defined only the byte stream , but character streams were quickly added. Byte streams can be used when reading or writing binary data. Character streams are designed for handling character I/O. Character streams use UNICODE . In Java, a character is 2 bytes Unicode is for the internationalization of Java in different languages . The Java I/O system is quite LARGE because of the TWO separate class hierarchies of bytes and streams.
  • 89. How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. Formatter output = new Formatter(&quot;temp.txt&quot;); output.format(&quot;%s&quot;, &quot;Java ITP 120&quot;); output.close(); Scanner input = new Scanner(new File(&quot;temp.txt&quot;)); System.out.println(input.nextLine());
  • 90. Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs . For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte -type value C7 in a binary file, because decimal 199 equals to hex C7 ( 12 x 16 + 7 = 192 + 7 = 199 decimal )
  • 91. Binary I/O Text I/O requires encoding and decoding. The JVM converts a Unicode character to file-specific encoding when writing a character, and coverts a file-specific encoding to a Unicode character when reading a character. Binary I/O does not require conversions . When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
  • 92. 2 Types of Stream Classes: Bytes & Characters The stream classes can be categorized into two types: byte streams and character streams . The InputStream/OutputStream class is the root of all byte stream classes The Reader/Writer class is the root of all character stream classes. The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer .
  • 93. Byte Stream Classes (note: “stream” )
  • 94. Character Stream Classes (Character = 2 bytes)
  • 95. Predefined Streams in Java All Java programs automatically import the java.lang package. The java.lang package defines a class called System which encapsulates several aspects of the runtime environment. The System class contains 3 predefined stream variables called: in, out, and err (System.in, System.out, System.err) These variables are declared as public and static with the System class. This means they can be used by any other part of your program and without a reference to a specific object in the System class.
  • 96. Predefined Streams in Java: System class System.in refers to the standard input stream which is the keyboard by default. (Keyboard ) System.out refers to the standard output stream which is the console by default. (Monitor) System.err refers to the standard error stream which is also the console by default. (Monitor) These streams may be redirected to any compatible I/O device .
  • 97. Predefined Streams in Java: System class System.in is an object of type InputStream. (byte stream) System.out is an object of type PrintStream. (byte stream) System.err is an object of type PrintStream. (byte stream) They are all byte streams and are a part of the original Java specification. They are NOT character streams ! (Unicode character = 2 bytes)
  • 98. Reading Keyboard Input // Read an array of bytes from the keyboard. import java.io.*; public class ReadBytes { public static void main(String[ ] args) throws IOException { byte data[ ] = new byte[10]; // Byte array “data” holds 10 bytes System.out.println(&quot;Enter some characters:&quot;); System.in.read(data); // Use the “read” method to read some bytes System.out.print(&quot;You entered: &quot;); for(int i=0; i < data.length; i++) System.out.print((char) data[i]); // Cast data to a character } // End main method } // End class ReadBytes
  • 99. Reading Keyboard Input Here is a sample run from the previous program: Enter some characters: (prompt from program) READ BYTES (User entered READ BYTES) You entered: READ BYTES (output from program)
  • 100. Writing Output to the Monitor // Demonstrate System.out.write(). Java program WriteDemo.java public class WriteDemo { public static void main(String[ ] args) { int b; // Program prints an ‘X’ on the monitor b = 'X'; // The character is an int System.out.write(b); // A byte stream; write low-order 8 bits System.out.write('\n'); // Print a newline character \n } // End of main( ) // print() and println() are easier to use than write() } // End of class WriteDemo
  • 101. Stream classes (Bytes & Characters) The java.io package provides two categories of classes: Byte stream readers and writers Character stream readers and writers At the top of the hierarchy for stream classes are the abstract classes InputStream and Output Stream The subclasses branch out and specializes into the different types of streams that they handle. InputData, OutputData, and ObjectInput interfaces are implemented by the classes that handle data, such as , int, double, char, etc., and objects. Only ObjectInput specifies methods for reading objects. DataInputStream - which is a subclass of FilterInputStream, which in turn is a subclass of InputStream – implements the InputData interface and can read primitive data, and objects from byte streams.
  • 102. Stream Classes FileInputStream can read raw streams of data from files. DataOutputStream can write primitive data; this class implements the OutputData interface RandomAccessFile implements both InputData and OutputData interfaces, therefore, it can read and write data to streams. ObjectOutputStream implements the ObjectOutput interface and can write object data to streams.
  • 103. InputStream Class (for reading bytes) The following methods are defined in InputStream and are often useful: public abstract int read() throws IOException Reads the next byte and returns its value in the range of 0 to 255. At the end of the stream, it returns a - 1. public int read(byte b[]) throws IOException Reads bytes into array b,, returns b.length if the number of available bytes is >= b.length. Returns the number of bytes read if the number of available bytes is < than b.length, and returns –1 at the end of the stream.
  • 104. InputStream Class (for reading bytes) The following methods are defined in InputStream and are often useful: public void close() throws IOException This method closes the input stream. public void available() throws IOException Returns the number of bytes that can be read from the input stream without blocking.
  • 105. InputStream Class (for reading bytes) The following method is defined in InputStream and is often useful: public long skip(long n) throws IOException Skip over and discard n bytes of data from the input stream. The actual number of bytes skipped is returned.
  • 106. Reading & Writing Files Using Byte Streams To create a byte stream linked to a file, use FileInputStream or FileOutputStream To open a file, create an object of one of these classes, specifying the name of the file as an argument to the constructor . Once the file is open, you can read from the file or write to the file. To read form a file, you may use the read( ) method. int read( ) throws IOException When you are done with a file, you should close it by calling close() void close( ) throws IOException Closing a file releases the system resources allocated to the file, allowing them to be used by another file.
  • 107. Reading & Writing Files Using Byte Streams /* Display a text file. To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. Command line usage: java ShowFile TEST.TXT */ // Program ShowFile.java follows on the next slide ->
  • 108. Reading & Writing Files Using Byte Streams public class ShowFile { public static void main(String[ ] args) throws IOException { int i; FileInputStream fin; // Declare file pointer try { fin = new FileInputStream(args[0]); } // Open the input file catch(FileNotFoundException exc) { System.out.println(“Error: “ + exc.getMessage( )); System.out.println(&quot;File Not Found&quot;); return; } } catch(ArrayIndexOutOfBoundsException exc) { System.out.println(“Error: “ + exc.getMessage( )); System.out.println(&quot;Usage is: java ShowFile File.txt &quot;); return; }
  • 109. Reading & Writing Files Using Byte Streams // Read bytes until EOF is encountered do { i = fin.read( ); // Read an integer if(i != -1) System.out.print((char) i); // Cast the int as a char } while( i != -1); // When i = -1, EOF is encountered fin.close( ); // Close the input file } // End of main method } // End of class ShowFile
  • 110. Writing to a File Using Byte Streams /* Java program to Copy a text file. To use this program, specify the name of the source file and the destination file. For example, to copy a file called File1.txt to a file called File2.txt , use the following on the command line: Usage: java CopyFile File1.txt File2.txt */
  • 111. Writing to a File Using Byte Streams // CopyFile.java Demo byte stream file operations import java.io.*; public class CopyFile { public static void main(String[ ] args) throws IOException { int i; FileInputStream fin; // Declare 2 byte stream files (pointers) FileOutputStream fout; // Output file pointer
  • 112. Writing to a File Using Byte Streams try { // outer try block // try to open input file try { // inner try fin = new FileInputStream(args[0]); } catch(FileNotFoundException exc) { System.out.println(“Error:” + exc.getMessage( ) ); System.out.println(&quot;Input File Not Found&quot;); return; }
  • 113. Writing to a File Using Byte Streams // open output file try { fout = new FileOutputStream(args[1]); } catch(FileNotFoundException exc) { System.out.println(“Error: “ + exc.getMessage()); System.out.println(&quot;Error Opening Output File&quot;); return; } } // End of outer try block
  • 114. Writing to a File Using Byte Streams catch(ArrayIndexOutOfBoundsException exc) { System.out.println(“Error: “ + exc.getMessage( ) ); System.out.println(&quot;Usage: CopyFile File1 File2&quot;); return; } try { // Try to copy file1 to file2 do { i = fin.read( ); // Read a byte if(i != -1) fout.write(i); // Write the byte to the output file } while(i != -1); // Loop while not at EOF (-1) } // End of try block catch(IOException exc) { System.out.println(&quot;File Error&quot;); } fin.close( ); // Close the input file fout.close( ); // Close the output file } // End of main( ) method } // End of class CopyFile
  • 115. Reading & Writing Binary Data So far, we have been reading and writing bytes containing ASCII bytes. You may want to create a file that contains other types of data such as integers, doubles, or shorts , that is: int, double, short, etc. In Java, to read and write binary values of the simple Java data types, you should use: DataInputStream and DataOutputStream (for binary data) DataOutputStream implements the OutputData interface . The OutputData interface defines methods that write all of Java’s simple data types to a file.
  • 116. Reading & Writing Binary Data Note: Binary data is NOT in human-readable text format, obviously. The constructor for DataOutputStream is: DataOutputStream(OutputStream outputStream ) outputStream is the stream to which the binary data is written.
  • 117. Reading & Writing Binary Data The constructor for DataInputStream is: DataInputStream(InputStream inputStream ) inputStream is the stream that is linked to the instance of DataInputStream being created. DataInputStream implements the DataInput interface which provides the methods for reading all of Java’s simple data types. DataInputStream uses an InputStream instance as its foundation, overlaying it with methods that read the various Java data types.
  • 118. Reading & Writing Binary Data Examples To create an input stream for the file in.dat ( bytes) DataInputStream infile = new DataInputStream(new FileInputStream(“in.dat”)); To create an output stream for the file out.dat: DataOutputStream outfile = new DataOutputStream(new FileOutputStream(“out.dat”));
  • 119. Reading & Writing Binary Data Common Input Methods Defined by DataInputStream (a byte stream) Input Method Purpose boolean readBoolean ( ) Reads a boolean byte readByte ( ) Reads a byte char readChar ( ) Reads a char double readDouble( ) Reads a double float readFloat ( ) Reads a float int readInt ( ) Reads an int long readLong ( ) Reads a long short readShort ( ) Reads a short
  • 120. Reading & Writing Binary Data Common Output Methods Defined by DataOutputStream ( byte stream) Output Method Purpose void writeBoolean (boolean val) writes the boolean specified by val void writeByte (int val) writes the low-order byte val void writeChar(int val) writes the value val as a char void writeDouble(double val) writes the double val void writeFloat(float val) writes the float val void writeInt(int val) writes the int val void writeLong(long val) writes the long val void writeShort(int val) writes val as a short
  • 121. Reading & Writing Binary Data Here is a Java program that demonstrates DataOutputStream and DataInputStream . It writes and then reads back various types of data to and from a file. // Write and then read back binary data. import java.io.*; public class RWData { public static void main(String[ ] args) throws IOException { DataOutputStream dataOut; // Declare output, input file pointers DataInputStream dataIn;
  • 122. Reading & Writing Binary Data int i = 120; double d = 1049.56; boolean b = true; try { dataOut = new DataOutputStream(new FileOutputStream(“testdata&quot;)); } catch(IOException exc) { System.out.println(“Error: “ + exc.getMessage( )); System.out.println(&quot;Cannot open file.&quot;); return; }
  • 123. Reading & Writing Binary Data try { // Write the binary data System.out.println(&quot;Writing &quot; + i); dataOut.writeInt(i); System.out.println(&quot;Writing &quot; + d); dataOut.writeDouble(d); System.out.println(&quot;Writing &quot; + b); dataOut.writeBoolean(b); System.out.println(&quot;Writing &quot; + 12.2 * 7.4); dataOut.writeDouble(12.2 * 7.4); }
  • 124. Reading & Writing Binary Data catch(IOException exc) { System.out.println(&quot;Write error: + exc.getMessage( )&quot;); } dataOut.close( ); System.out.println(); // Print a blank line // Now, read them back. try { dataIn = new DataInputStream(new FileInputStream(&quot;testdata&quot;)); } catch(IOException exc) { System.out.println(&quot;Cannot open file. + exc.getMessage( )&quot;); return; }
  • 125. Reading & Writing Binary Data try { // Read the binary data i = dataIn.readInt(); System.out.println(&quot;Reading &quot; + i); d = dataIn.readDouble(); System.out.println(&quot;Reading &quot; + d); b = dataIn.readBoolean(); System.out.println(&quot;Reading &quot; + b); d = dataIn.readDouble(); System.out.println(&quot;Reading &quot; + d); }
  • 126. Reading & Writing Binary Data catch(IOException exc) { System.out.println(&quot;Read error.“ + exc.getMessage( ) ); } dataIn.close(); } // End of main ( ) } // End of class RWData The output from the previous program follows: Writing 120 Reading 120 Writing 1023.56 Reading 1049.56 Writing true Reading true Writing 90.28 Reading 90.28
  • 127. Reader class methods for reading characters The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation. Remember: A character is 2 bytes ! public abstract int read() throws IOException public int read(char b[]) throws IOException public void close() throws IOException public void skip() throws IOException
  • 128. OutputStream ( bytes) & Writer (for characters) Like InputStream (for reading bytes ) and Reader (for reading characters ), OutputStream and Writer are the counterparts. They are the base classes for for all output streams of bytes and characters, respectively. The next slide shows methods which are in both OutputStream and Writer . See next slide ->
  • 129. OutputStream (Writing bytes) public abstract void write(int b) throws IOException Write a byte b (for OutputStream) or a charcter (for Writer) public void write(byte[] b) throws IOException This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer) public void close() throws IOException This method closes the output stream. public void flush() throws IOException Flush the output stream and send any buffered data in the stream to its destination.
  • 130. Writer (Writing characters) (Same as OutputStream) public abstract void write(int b) throws IOException Write a byte b (for OutputStream) or a character (for Writer) public void write(byte[] b) throws IOException This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer) public void close() throws IOException This method closes the output stream. public void flush() throws IOException Flush the output stream and send any buffered data in the stream to its destination.
  • 131. Console Input using Character Streams For Java code that will be internationalized, inputting data from the console using Java’s character-based streams is a better , more convenient way to read characters from the keyboard than using byte streams. Since System.in is a byte-stream, you need to wrap System.in inside of some type of Reader . The best class for reading console input is BufferedReader which supports a buffered input stream. (BufferedReader inherits from Reader) But, you cannot construct a BufferedReader directly from System.in
  • 132. Console Input using Character Streams You must first convert the input from System.in from a byte stream into a character stream. To do this, you must use InputStreamReader. InputStreamReader converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in , use the following constructor: InputStreamReader ( InputStream inputStream ) Since System.in refers to an object of type InputStream, it can be used for inputStream such as in: InputStreamReader(System.in)
  • 133. Console Input using Character Streams Next, using the object produced by InputStreamReader, construct a BufferedReader using the following constructor: BufferedReader(Reader inputReader ) Here , inputReader is the stream that is linked to the instance of BufferedReader being created.
  • 134. Console Input using Character Streams Putting it all together, the following line of code creates a BufferReader that is connected to the keyboard. BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); After the above statement executes, “br” will be a character -based stream that is linked to the console thru System.in (which reads bytes)
  • 135. Console Input using Character Streams Reading Characters Characters can be read from System.in using the read( ) method defined by BufferedReader. BufferedReader defines the following versions of read( ) int read( ) throws IOException int read(char data[ ] ) throws IOException int read(char data[ ], int start, int max) throws IOException
  • 136. Console Input using Character Streams int read( ) throws IOException reads a single Unicode character and returns a -1 when the end of the stream is reached. int read(char data [ ]) throws IOException reads characters from the input stream until: (1) the array is full, (2) EOF is reached, or (3) an error occurs. int read(char data [ ], int start , int max ) throws IOException reads input into array data beginning at the location specified by start , storing up to max characters. It returns the number of characters read or -1 when the end of the stream is reached. Pressing the [Enter] key generates an end-of-stream condition.
  • 137. Console Input using Character Streams The following program demonstrates the read( ) method by reading characters from the console until the user types a period. // Use a BufferedReader to read characters from the console. import java.io.*; public class ReadChars { public static void main(String[ ] args) throws IOException {
  • 138. Console Input using Character Streams BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(&quot;Enter some characters; period to quit.&quot;); // read characters do { c = (char) br.read(); // Cast the character to a byte System.out.println(c); // Print the character } while(c != '.'); // Loop as long as the input char is not a period } // End of main method } // End of ReadChars class
  • 139. Console Input using Character Streams Output from the previous program could be: Enter some characters; period to quit. I T P J A V A . <- note the period character which stopped the input stream
  • 140. Console Input using Character Streams Reading Character Strings from the Keyboard … To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. The general form is: String readLine( ) throws IOException It returns a string object that contains the characters read. It returns null if an attempt is made to read beyond the end of the stream.
  • 141. Console Input using Character Streams The following program demonstrates BufferedReader and the readLine() method. The program reads and displays lines of text until the user enters the word “stop” // Read a string from console using a BufferedReader. import java.io.*; class ReadLines { public static void main(String[ ] args) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str;
  • 142. Console Input using Character Streams System.out.println(&quot;Enter lines of text.&quot;); System.out.println(&quot;Enter 'stop' to quit.&quot;); do { str = br.readLine(); System.out.println(str); } while(!str.equals(&quot;stop&quot;)); } // End of main method } // End of class ReadLines
  • 143. Console Output using Character Streams The preferred method of writing to the console (monitor) when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class makes it easier to internationalize Java programs. PrintWriter has several constructors, but this is the one to be used in the demonstration program which is on the following slides: PrintWriter(OutputStream outputStream , boolean flushOnNewline)
  • 144. Console Output using Character Streams PrintWriter(OutputStream outputStream , boolean flushOnNewline) Here, outputStream is an object of type OutputStream. flushOnNewLine controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewLine is true flushing automatically takes place. If flushOnNewLine is false , flushing is not automatic.
  • 145. Console Output using Character Streams To write to the console (monitor) using a PrintWriter , specify System.out for the output stream and flush the stream after each call to println( ). For example, the following line of code creates a PrintWriter that is connected to console (monitor) output. PrintWriter pw = new PrintWriter(System.out, true); The Java program on the next slide demonstrates a PrintWriter 
  • 146. Console Output using Character Streams // Demonstrate PrintWriter. import java.io.*; public class PrintWriterDemo { public static void main(String[ ] args) { PrintWriter pw = new PrintWriter(System.out, true); int i = 120; double d = 123.67;
  • 147. Console Output using Character Streams pw.println(&quot;Using a PrintWriter.&quot;); // PrintWriter Demo pw.println(i); pw.println(d); pw.println(i + &quot; + &quot; + d + &quot; is &quot; + i +d); } // End of main( ) method } // End of class PrintWriterDemo The output from the previous program is: Using a PrintWriter. 120 123.67 120 + 123.67 is 243.67
  • 148. File Input & Output using Character Streams In general, to perform character-based file I/O, you will use the FileReader and FileWriter classes. Using a FileWriter FileWriter creates a Writer that you can use to write to a file. FileWriter is derived from OutputStreamWriter and Writer classes Commonly used constructors are: FileWriter (String fileName) throws IOException FileWriter (String fileName, boolean append ) throws IOException fileName is the full path name of the file. If append is true, then output is appended to the end of the file. Otherwise, the file is overwritten.
  • 149. File I / O using Character Streams FileWriter // A simple keyboard-to-disk utility that demonstrates a FileWriter. import java.io.*; public class KtoD { public static void main(String[ ] args) throws IOException { String str; FileWriter fw; BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
  • 150. File I / O using Character Streams FileWriter try { fw = new FileWriter(&quot;test.txt&quot;); // Try to open the file } catch(IOException exc) { System.out.println(“Error: “ + exc.getMessage( ) ); System.out.println(&quot;Cannot open output file.&quot;); return ; }
  • 151. File I / O using Character Streams FileWriter System.out.println(&quot;Enter text ('stop' to quit).&quot;); do { System.out.print(&quot;: &quot;); str = br.readLine( ); if(str.compareTo(&quot;stop&quot;) == 0) break; str = str + &quot;\r\n&quot;; // add carriage return & newline fw.write(str); } while(str.compareTo(&quot;stop&quot;) != 0); fw.close( ); } // End of main ( ) method } // End of class KtoD
  • 152. File I / O using Character Streams FileReader The FileReader class creates a Reader that you can use to read the contents of a file. FileReader is derived from the InputStreamReader and Reader classes. It has access to the methods in those classes. The most common constructor is: FileReader(String fileName ) throws FileNotFoundException where fileName is the full path name of the file. It throws a FileNotFoundException if the file does not exist.
  • 153. File I / O using Character Streams FileReader The following program reads a text file called “test.txt” and displays the information on the screen. // A simple disk-to-screen utilitiy that demonstrates a FileReader. import java.io.*; class DtoS { public static void main(String[ ] args) throws Exception { FileReader fr = new FileReader(&quot;test.txt&quot;); BufferedReader br = new BufferedReader(fr); String s;
  • 154. File I / O using Character Streams FileReader while((s = br.readLine()) != null) { System.out.println(s); } fr.close( ); // Close the file } // End of main( ) method } // End of DtoS class
  • 155. The File Class: Objectives To discover file properties, delete and rename files using the File class To understand how I/O is processed in Java To distinguish between text I/O and binary I/O To read and write characters using FileReader and FileWriter To improve the performance of text I/O using BufferedReader and BufferedWriter To write primitive values, strings, and objects as text using PrintWriter and PrintStream To read and write bytes using FileInputStream and FileOutputStream To read and write primitive values and strings using DataInputStream / DataOutputStream To store and restore objects using ObjectOutputStream and ObjectInputStream , and to understand how objects are serialized and what kind of objects can be serialized To use RandomAccessFile for both read and write.
  • 156. The File Class The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string. The File class is a wrapper class for the file name and its directory path.
  • 157. Obtaining file properties and manipulating file
  • 158. Example Using the File Class TestFileClass.java Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. Figure 1 shows a sample run of the program on Windows, and Figure 2 a sample run on Unix (Windows) (Unix)
  • 159. The File Class and Processing External Files The File class provides an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. You can create a new File object using the following statement: File myfile = new File (“myfile.dat”); You can use the File class to check properties of files, such as whether the file exists , or is readable , or updateable .
  • 160. The File Class and Processing External Files You can use the getName( ) method to get the name of the file. For example, if (myfile.exists( ) ) System.out.println(“File “ + myfile.getName( ) + “ already exists”); The following statement creates a file using the full path using the Windows operating system: File myfile = new File(“C:\\Java\\myfile.data”);
  • 161. The File Class and Processing External Files You can use the getPath( ) method to get the full path of the file and the getParent( ) method to get the directory that contains the file. For example, if (myfile.exists( ) ) { System.out.println(“The full path is “ + myfile.getPath( ) ); System.out.println(“The directory is “ + myfile.getParent( ) ); }
  • 162. Demo Program: TestFileClass.java // TestFileClass.java: Demonstrate the File class Chapt 18 I/O ITP120 import java.io.*; import java.util.*; public class TestFileClass { public static void main(String[] args) { // Create a File object File file = new File(&quot;.&quot;, &quot;images&quot; + File.separator + &quot;bill_gates.gif&quot;); System.out.println(&quot;Does it exist? &quot; + file.exists()); System.out.println(&quot;Can it be read? &quot; + file.canRead()); System.out.println(&quot;Can it be written? &quot; + file.canRead()); System.out.println(&quot;Is it a directory? &quot; + file.isDirectory()); System.out.println(&quot;Is it a file? &quot; + file.isFile()); System.out.println(&quot;Is it absolute? &quot; + file.isAbsolute()); System.out.println(&quot;Is it hidden? &quot; + file.isHidden()); System.out.println(&quot;What is its absolute path? &quot; + file.getAbsolutePath());
  • 163. Demo Program: TestFileClass.java try { System.out.println(&quot;What is its canonical path? &quot; + file.getCanonicalPath()); } catch (IOException ex) { } System.out.println(&quot;What is its name? &quot; + file.getName()); System.out.println(&quot;What is its path? &quot; + file.getPath()); System.out.println(&quot;When was it last modified? &quot; + new Date(file.lastModified())); System.out.println(&quot;What is the path separator? &quot; + File.pathSeparatorChar); System.out.println(&quot;What is the name separator? &quot; + File.separatorChar); } }
  • 164. Processing External Files Again, you must use file streams to read from or write to a disk file. Once again, you can use FileInputStream or FileOutputStream for byte streams. And you can use FileReader or FileWriter for character streams.
  • 165. File I/O Stream Constructors To create a file stream, use these constructors: public FileInputStream (String filenameString) // Byte stream constructors public FileInputStream (File file) public FileOutputStream (String filenameString) // Byte stream constructor public FileOutputStream (File file) public FileReader (String filenameString) // Character stream constructors public FileReader (File file) public FileWriter (String filenameString) // Character stream constructor public FileWriter (File file)
  • 166. File I/O Stream Constructors Constructing instances of FileInputStream , FileOutputStream , FileReader , and FileWriter from file names: FileInputStream infile = new FileInputStream(&quot;in.dat&quot;); FileOutputStream outfile = new FileOutputStream(&quot;out.dat&quot;); FileReader infile = new FileReader(&quot;in.dat&quot;); FileWriter outfile = new FileWriter(&quot;out.dat&quot;);
  • 167. Demo Program: TestFileReader.java // TestFileReader.java Chapter 18 I/O ITP 120 import java.io.*; public class TestFileReader { public static void main(String[ ] args) { FileReader input = null; try { // Create an input stream input = new FileReader(&quot;temp.txt&quot;); int code; // Repeatedly read a character and display it on the console while ((code = input.read()) != -1) System.out.print((char)code); } // End of try block
  • 168. Demo Program: TestFileReader.java System.out.println(&quot;File temp.txt does not exist&quot;); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } } } // End of class TestFileReader
  • 169. Demo Program: TestFileWriter.java // TestFileWriter.java Chapter 18 File I/O ITP 120 import java.io.*; public class TestFileWriter { public static void main(String[ ] args) throws IOException { // Create an output stream to the file FileWriter output = new FileWriter(&quot;temp.txt&quot;, true); // Output a string to the file output.write(“ NVCC Introduction to Java Programming ITP 120 !!!&quot;); // Close the stream output.close(); } }
  • 171. Processing External Files The previous diagram shows that: FileInputStream, fis, is used to read data (bytes) from a file FileOutputStream, fos, is used to write data (bytes) to a file Command line: java CopyFileUsingByteStream f1.txt f2.txt See the Java program CopyFileUsingByteStream on the following slides 
  • 172. Processing External Files // CopyFileUsingByteStream.java For Copying files (byte streams) import java.io.*; public class CopyFileUsingByteStream { // Main method: args[0] for sourcefile and args[1] for target file public static void main(String[ ] args) { // Declare input and output file streams FileInputStream fis = null; FileOutputStream fos = null;
  • 173. Processing External Files if (args.length !=2) // args[0] is source file { // args[1] is target file System.out.println( &quot;Usage: java CopyFileUsingByteStream f1 f2&quot;); System.exit(0); // Stop the program }
  • 174. Processing External Files try { // Create file input stream fis = new FileInputStream(new File(args[0])); // Create file output stream if the file does not exist File outFile = new File(args[1]); if (outFile.exists()) { System.out.println(&quot;file &quot; + args[1] + &quot; already exists&quot;); return; }
  • 175. Processing External Files else fos = new FileOutputStream(args[1]); // FileOutputStream // Display the file size System.out.println(&quot;The file &quot; + args[0] + &quot; has &quot;+ fis.available() + &quot; bytes&quot;);
  • 176. Processing External Files // Continuously read a byte from fis and write it to fos int r; while ((r = fis.read()) != -1) // EOF is -1 fos.write((byte)r); } catch (FileNotFoundException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;File not found: &quot; + args[0]); }
  • 177. Processing External Files catch (IOException ex) { System.out.println(“Some IO Exception occurred”); System.out.println(“Error: “ + ex.getMessage( )); } Continues to next slide 
  • 178. Processing External Files finally { try { if (fis != null) fis.close(); // Close the input & output files if (fos != null) fos.close(); } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); } } // End of finally block } // End of main method } // End of class CopyFileUsingByteStream
  • 179. Filter Streams Filter streams are streams that filter bytes or characters for some purpose. If you want to read integers , doubles , or Strings , you need a filter class to wrap the input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters . Use FilterInputStream and FilterOutputStream when you need to process primitive numeric types.
  • 180. Filter Streams To process strings , use BufferedReader and PushbackReader to filter characters. Note: FilterInputStream and FilterOutputStream are abstract classes.
  • 181. FilterInputStream subclasses DataInputStream handles binary formats for all primitive data types. BufferedInputStream gets data from the buffer and then reads them from the stream if necessary. LineNumberInputStream keeps track of how many lines are read. PushBackInputStream allows single-byte look-a-head. Looks at a byte and pushes it back to the stream if the byte read is NOT the desired byte.
  • 182. FilterOutputStream subclasses DataOutputStream outputs the binary formats for all primitive data types which is useful if another program uses the output . BufferedOutputStream outputs to the buffer first and then to the stream if necessary. You may also call the flush( ) method to write the buffer to the stream. PrintStream outputs the Unicode format of all primitive types which is useful if the format is output to the console .
  • 183. Data Streams (bytes) The data streams ( DataInputStream and DataOutputStream ) read and write Java primitive types in a machine-independent fashion. This enables you to write a data file for one computer and read it on another computer that has a different operating system or file structure.
  • 184. DataInputStream Methods defined in the DataInput Interface int readByte() throws IOException int readShort() throws IOException int readInt() throws IOException int readLong() throws IOException float readFloat() throws IOException double readDouble() throws IOException char readChar() throws IOException boolean readBoolean() throws IOException String readUTF() throws IOException
  • 185. DataOutputStream Methods defined in the DataOutput interface void writeByte(byte b) throws IOException void writeShort(short is) throws IOException void writeInt(int i) throws IOException void writeLong(long l) throws IOException void writeFloat(float f) throws IOException void writeDouble(double d) throws IOException void writeChar(char c) throws IOException void writeBoolean(boolean b) throws IOException void writeBytes(String s) throws IOException void writeChars(String s) throws IOException void writeUTF(String s) throws IOException
  • 186. DataInputStream & DataOutput Stream Constructors Data streams are used as wrappers on existing input and output streams to filter data in the original stream. DataInputStream infile = new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); The above creates an input file for in.dat. DataOutputStream outfile = new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); The above creates an output file for out.dat.
  • 187. Using Data Streams The next example shows a program that: Creates 10 random integers, Stores them in a data file, Retrieves data from the file, Displays the integers on the console. See next slide 
  • 188. Using Data Streams Demo Example // TestDataStreams.java: Create a file, store it in binary form, and // display the contents of the file on the console import java.io.*; public class TestDataStreams { // Main method public static void main(String[ ] args) { // Declare data input and output streams DataInputStream dis = null; DataOutputStream dos = null;
  • 189. Using Data Streams Demo Example // Construct a temp file File tempFile = new File(&quot;mytemp.dat&quot;); // Check if the temp file exists if (tempFile.exists()) { System.out.println(&quot;The file mytemp.dat already exists,&quot; +&quot; delete it, rerun the program&quot;); System.exit(0); }
  • 190. Using Data Streams Demo Example // Write data try { // Create data output stream for tempFile dos = new DataOutputStream(new FileOutputStream(tempFile)); for (int i=0; i<10; i++) dos.writeInt((int)(Math.random()*1000)); }
  • 191. Using Data Streams Demo Example catch (IOException ex) { System.out.println(ex.getMessage( ) ); } finally { try { if (dos != null) dos.close( ); // Close the file(s) } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); }
  • 192. Using Data Streams Demo Example // Read data try { // Create data input stream dis = new DataInputStream(new FileInputStream(tempFile)); for (int i=0; i<10; i++) System.out.print(&quot; &quot;+dis.readInt ( ) ); // Display the integers }
  • 193. Using Data Streams catch (FileNotFoundException ex) { System.out.println(&quot;File not found“ + ex.getMessage( ) );); } catch (IOException ex) { System.out.println(ex.getMessage()); }
  • 194. Using Data Streams finally { try { if (dis != null) dis.close( ); // Close the file(s) } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) )); } } // End of finally block } // End of main method } // End of class TestDataStreams
  • 195. Using Data Streams Demo Example The previous Java program TestDataStreams.java creates a DataInputStream object named “dis” wrapped on FileInputStream and creates a DataOutputStream object “dos” wrapped on FileOutputStream Conceptually, Program  DataInputStream dis <-- fileInputStream <--mytemp.dat  DataOutputStream dos  fileOutputStream  mytemp.dat The program uses a temporary file, mytemp.dat , to store data. The program creates mytemp.dat if it does not exist and writes 10 random integers into mytemp.dat. The data in mytemp.dat is in binary format.
  • 196. Character Classes The classes that handle characters have at the top of their hierarchy, Reader and Writer The subclasses branch out to provide specialized functionality. FileReader provides functionality for reading streams of characters from files. BufferedReader buffers character streams for efficiency FileWriter for writing character streams to files. PrintWriter for writing character streams.
  • 197. File Class File class provides functionality for working directly with files in the operating system The File class provides overloaded constructors for creating File objects. A File object can be created by giving the name of the file: File inputFile = new File(“in.dat”); // Same directory File myInputFile = new File(“C:\\myDirectory\\in.dat”); A File Object can refer to either a file or directory File theDir = new File(“C:\\myDir”); //File object theDir refers to a directory Some File class methods: exists() that tests if the named file already exist. mkdir( String st ) for creating directories list() for listing the contents of directories getPath() gets the path of the named file length() returns the file size in bytes
  • 198. File Class Example: DirectoryContents.java listing the contents of a directory using File class import java.io.*; public class DirectoryContents { public static void main(String[ ] args) { File myDir = new File(“C:\\&quot;); if(myDir.isDirectory( ) ) { System.out.println(&quot;Contents of directory &quot; + myDir ); String[ ] contents = myDir.list(); for( int I = 0; I < contents.length; I++) System.out.println(contents[ I ] ); } // End of “if” block } // End of main method } // End of class DirectoryContents
  • 199. Using Java I/O Many of the methods including constructors of Java.io classes throw exceptions: The most commonly thrown is IOException. Reading data from the keyboard BufferedReader in = new BufferedReader(new InputStreamReader(System.in); An InputStreamReader is like an adapter, it reads byte streams and converts it into character streams BufferedReader wraps the InputStreamReader to provide extra functionality, allowing to buffer the input to support readLine()
  • 200. Using Java I/O Example Reading strings from the keyboard Import java.io.* public class ReadStringFromKeyboard { public static void main(String[ ] args) { // Converts from bytes to characters BufferedReader in = new BufferedReader(new InputStreamReader (System.in)); String yourInput; try { System.out.println(&quot;Please enter any string and hit the return key when done:&quot;); yourInput = in.readLine( ); System.out.println(&quot;\nBelow is the input you entered&quot;); System.out.println(yourInput); } catch (IOException ex) { System.out.println(“Could not read from the keyboard” } } // End of main method } // End of class ReadStringFromKeyboard
  • 201. Using Java I/O Example: Reading from an external file public class ReadFromFile { public static void main(String[ ] args) { String st = null; File inputFileName = null; FileReader inputFile = null; BufferedReader in = null; try { inputFileName = new File(&quot;Input1.txt&quot;); inputFile = new FileReader(inputFileName); in = new BufferedReader(inputFile); /* Note: The above 3 lines can be combined in one line as below in = new BufferedReader(new FileReader(new File(&quot;Input1.txt&quot;))); */
  • 202. Using Java I/O Example Continued // Now let us start reading from the opened file while((st = br.readLine()) != null ) { System.out.println(st); // Print the string } } catch (FileNotFoundException fnex) { System.out.println(“Error: “ + fnex.getMessage( ) ); System.out.println(&quot;Input file was not found&quot;); } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;There was a problem reading from the file&quot;); }
  • 203. Using Java I/O Example continued finally { if( br != null) try { br.close( ); // Close the file } catch (Exception ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;There was a problem with closing the file&quot;); } } // End finally block } // End of main method } // End of class
  • 204. Print Streams The data output stream outputs a binary representation of data, so you cannot view its contents as text. In Java, you can use print streams to output data into files. These files can then be viewed as text. The PrintStream and PrintWriter classes provide the functionality for doing this. PrintStream is for bytes PrintWriter is for characters (Unicode)
  • 205. Print Streams: PrintWriter Constructors PrintWriter(Writer out) PrintWriter(Writer out, boolean autoFlush) PrintWriter(OutputStream out) PrintWriter(OutputStream out, boolean autoFlush)
  • 206. Print Streams: PrintWriter Methods (for chars) void print(Object o) void print(String s) void println(String s) void print(char c) void print(char[] cArray) void print(int i) void print(long l) void print(float f) void print(double d) void print(boolean b)
  • 207. Print Streams: PrintWriter Methods Note: On the previous slide, you may replace print with println in the various method definitions. The println method, which prints the object, is followed by a new line. When the object is passed to print or println , the object’s toString( ) method converts it to a String object.
  • 208. Demo Program Example Using Print Streams The next sample Java program creates a print stream, pw , of PrintWriter , wrapped on FileOutputStream , for text format. pw = new PrintWriter(new FileOutputStream(tempFile),true); The program creates the file, arg[0], if that file does not already exist. The program writes 10 random integers into the file by using the data output stream, then closes the stream. The data file could be viewed by using the type command in DOS
  • 209. Using Print Streams: Demo Example // TestPrintWriters.java: Create a text file // using PrintWriter import java.io.*;   public class TestPrintWriters { // Main method: args[0] is the output file public static void main(String[] args) { // Declare print stream PrintWriter pw = null;  
  • 210. Using Print Streams: Demo example // Check usage if (args.length != 1) { System.out.println(&quot;Usage: java TestPrintWriters file&quot;); System.exit(0); }   File tempFile = new File(args[0]);  
  • 211. Using Print Streams: Demo Example if (tempFile.exists()) { System.out.println(&quot;The file &quot; + args[0] + &quot; already exists, delete it, rerun the program&quot;); System.exit(0); }
  • 212. Using Print Streams: Demo Example // Write data try { // Create print writer stream for tempFile pw = new PrintWriter(new FileOutputStream(tempFile), true); for (int i=0; i<10; i++) pw.print(&quot; &quot;+(int)(Math.random()*1000)); }
  • 213. Using Print Streams: Demo Example catch (IOException ex) { System.out.println(ex.getMessage()); } finally { // Close files if (pw != null) pw.close(); } } }
  • 214. Using Print Streams: Demo Example C:\test>java TestPrintWriters Usage: java TestPrintWriters filename C:\test>java TestPrintWriters test.dat C:\test>type test.dat (Use the TYPE command to see data in file) 567 915 7 23 677 455 402 997 290 549
  • 216. Using Java I/O Example: WriteToFile.java Writing text to external files import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class WriteToFile { public WriteToFile( ) { } // Empty constructor
  • 217. Using Java I/O Example: WriteToFile.java (continued) public static void main (String[ ] args) { File outputFileName = null; PrintWriter outToFile = null; try { outputFileName = new File(&quot;outFile1.txt&quot;); outToFile = new PrintWriter( new FileWriter(outputFileName)); // Now we can start writing to file outToFile.println(&quot;This message is going to the output file&quot;); outToFile.println(&quot;This will be line two in the output file&quot;); outToFile.println(&quot;We can write the output file any time we want&quot;); outToFile.flush( ); // Flush output file }
  • 218. Using Java I/O Example 18.6 catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;There was a problem writing to the output file&quot;); } finally { if ( outToFile != null ) outToFile.close( ); // Close output file } // End of finally block } // End of main method } // End of class WriteToFile
  • 219. Buffered Streams in Java Java introduces buffered streams that speed up input and output by reducing the number of reads and writes. In the case of input, a bunch of data is read all at once instead of one byte at a time. In the case of output, data are first cached into a buffer, then written all together to the file. Using buffered streams is highly recommended.
  • 220. Buffered Stream Constructors BufferedInputStream (InputStream in) BufferedInputStream (InputStream in, int bufferSize) BufferedOutputStream (OutputStream in) BufferedOutputStream (OutputStream in, int bufferSize) BufferedReader(Reader in) BufferedReader(Reader in, int bufferSize) BufferedWriter(Writer out) BufferedWriter(Writer out, int bufferSize)
  • 221. Demo Program: ViewFile.java (A Text Viewer program) This case study writes a program that views a text file in a text area. The user enters a filename in a text field and clicks the View button; the file is then displayed in a text area.
  • 222. Buffered Streams in Java ViewFile program // ViewFile.java: Read a text file and store it in a text area import java.awt.*; // Buffered I/O example (Demo program) import java.awt.event.*; import java.io.*; import javax.swing.*; public class ViewFile extends MyFrameWithExitHandling implements ActionListener { // Button to view view private JButton jbtView = new JButton(&quot;View&quot;);
  • 223. Buffered Streams in Java ViewFile program // Text field to receive file name private JTextField jtf = new JTextField(12); // Text area to display file private JTextArea jta = new JTextArea(); public static void main(String [ ] args) // Main method { ViewFile frame = new ViewFile(); frame.setTitle(&quot;View File Program in Java&quot;); frame.setSize(400, 300); frame.setVisible(true); }
  • 224. Buffered Streams in Java ViewFile program // Constructor public ViewFile() { // Panel p to hold a label, a text field, and a button Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Label(&quot;Filename&quot;), BorderLayout.WEST); p.add(jtf, BorderLayout.CENTER); jtf.setBackground(Color.yellow); jtf.setForeground(Color.red); p.add(jbtView, BorderLayout.EAST);
  • 225. Buffered Streams in Java ViewFile program // Add jtaFile to a scroll pane JScrollPane jsp = new JScrollPane(jtaFile); // Add jsp and p to the frame getContentPane().add(jsp, BorderLayout.CENTER); getContentPane().add(p, BorderLayout.SOUTH); // Register listener jbtView.addActionListener(this); }
  • 226. Buffered Streams in Java ViewFile program // Handle the &quot;View&quot; button public void actionPerformed(ActionEvent e) { if (e.getSource() == jbtView) showFile(); }
  • 227. Buffered Streams in Java ViewFile program // Display the file in the text area private void showFile() { // Use a BufferedStream to read text from the file BufferedReader infile = null; // Get file name from the input text field at the bottom String filename = jtf.getText().trim(); String inLine;
  • 228. Buffered Streams in Java ViewFile program try { // Create a buffered stream infile = new BufferedReader(new FileReader(filename)); // Read a line inLine = infile.readLine(); boolean firstLine = true;
  • 229. Buffered Streams in Java ViewFile program while (inLine != null) // Append the line to the text area { if (firstLine) { firstLine = false; jtaFile.append(inLine); } else { jta.append(&quot;\n&quot; + inLine); } inLine = infile.readLine(); } } // End of try block
  • 230. Buffered Streams in Java ViewFile program catch (FileNotFoundException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(&quot;File not found: &quot; + filename); } catch (IOException ex) { System.out.println(ex.getMessage()); }
  • 231. Buffered Streams in Java ViewFile program finally { try { if (infile != null) infile.close( ); // Close input file } catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( )); } } // End of finally block } // End of method showFile() } // End of class ViewFile
  • 232. Buffered Streams in Java ViewFile program Demostrate the ViewFile program by running: java ViewFile (at the command prompt) Wait for Java window to appear. then type Comcast1.txt or the name of some text file in the text box at the bottom of the Java window. Look at the contents on the text file in the Java window.
  • 233. Text Input & Output on the Console In previous chapters, you used text input and output with the System class. The System class, as you have already seen, contains 3 I/O objects: System.in, System.out, and System.err . The objects in, out and err are static variables. The variable in is of InputStream type and out , err are of PrintStream type. (byte streams) These are the basic objects that all java programmers use to get input from the keyboard, send output to the screen, and display error messages.
  • 234. Text Input & Output on the Console To perform console output, you can use any of the methods for PrintStream in the System.out object. To get input from the keyboard, you can use the following statements to read a string from the keyboard See next slide   AND ALSO VIEW THE EXPANDED VERSION of MyInput.java which follows thereafter
  • 235. Text Input & Output on the Console BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1); // Note: the 1 above means a buffer size of 1 // Declare and initialize the string String string = &quot; &quot;; // Get the string from the keyboard try { string = br.readLine(); } catch (IOException ex) { System.out.println(ex); }
  • 236. Text I/O on the Console MyInput.java (full) public class MyInput // Expanded version { // Read a string from the keyboard public static String readString() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1); // Declare and initialize the string String string = &quot; &quot;; // Get the string from the keyboard try { string = br.readLine(); } catch (IOException ex) { System.out.println(ex) ; }
  • 237. Text I/O on the Console MyInput.java (full) // Return the string obtained from the keyboard return string; } // Read an int value from the keyboard public static int readInt() { return Integer.parseInt(readString()); }
  • 238. Text I/O on the Console MyInput.java (full) // Read a double value from the keyboard public static double readDouble() { return Double.parseDouble(readString()); } // Read a byte value from the keyboard public static double readByte() { return Byte.parseByte(readString()); }
  • 239. Text I/O on the Console MyInput.java (full) // Read a short value from the keyboard public static double readShort() { return Short.parseShort(readString()); } // Read a long value from the keyboard public static double readLong() { return Long.parseLong(readString()); }
  • 240. Text I/O on the Console MyInput.java (full) // Read a float value from the keyboard public static double readFloat() { return Float.parseFloat(readString()); } }
  • 241. Random Access Files (byte streams) Java allows you to access the contents of a file in random order To do this, you will use RandomAccessFile which encapsulates a random-access file. RandomAccessFile is a stream class derived from Object RandomAccessFile is NOT derived from InputStream or OutputStream. RandomAccessFile implements interfaces InputData & OutputData InputData & OutputData define the basic I/O methods. You can also position the file pointer within the file using the method seek ( )
  • 242. Random Access Files (Constructor(s)) The constructor for RandomAccessFile is: RandomAccessFile (String filename , String access ) throws FileNotFoundException The name of the file is passed in filename The term access determines what type of file access is permitted. If the access is “r”, the file is read-only. If the access is “rw”, the file is opened in read-write mode.
  • 243. Random Access Files (Methods) The method seek ( ) is used to set the current position of the file pointer within a random access file: void seek (long newpos ) throws IOException newpos specifies the new position, in bytes , of the file pointer from the beginning of the file. After a call to seek( ), the next read or write operation will occur at the new file position.
  • 244. Random Access Files (Methods) public long getFilePointer ( ) throws IOException Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. public long length ( ) throws IOException Returns the length of the file in bytes. public final void writeChar (int v) throws IOException Writes a character to the file as a 2-byte Unicode character with the higher byte written first. public final void writeChars(String s) throws IOException Writes a string to a file as a sequence of characters.
  • 245. Random Access Files RandomAccessFile implements the read ( ) and write ( ) methods. It also implements the InputData and OutputData interfaces , which means that methods to read and write the simple data types such as readInt( ) and writeDouble( ) are available. The slides which follow show a Java program that demonstrates random access file I/O. The program writes 6 double numbers to a file and then reads them back in a non-sequential order.
  • 246. Random Access Files // Demonstrate random access files RandonAccessDemo.java import java.io.*; public class RandomAccessDemo { public static void main(String[ ] args) throws IOException { double data[ ] = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 }; double d; RandomAccessFile raf;
  • 247. Random Access Files try { raf = new RandomAccessFile(&quot;random.dat&quot;, &quot;rw&quot;); } catch(FileNotFoundException ex) { System.out.println(&quot;Cannot open file.&quot;); System.out.println(“Error: “ + ex.getMessage( ) ); return ; }
  • 248. Random Access Files // Write values to the file. for (int i=0; i < data.length; i++) { try { raf.writeDouble(data[i]); } catch(IOException ex) { System.out.println(“Error: “ + ex.getMessage( )); System.out.println(&quot;Error writing to file.&quot;); return ; } } // End of “for” loop
  • 249. Random Access Files try { // Now, read back specific values raf.seek(0); // seek to first double d = raf.readDouble(); System.out.println(&quot;First value is &quot; + d); raf.seek(8); // seek to second double d = raf.readDouble(); System.out.println(&quot;Second value is &quot; + d); raf.seek(8 * 3); // seek to fourth double d = raf.readDouble(); System.out.println(&quot;Fourth value is &quot; + d); System.out.println();
  • 250. Random Access Files // Now, read every other value. System.out.println(&quot;Here is every other value: &quot;); for (int i=0; i < data.length; i+=2) { raf.seek(8 * i); // seek to ith double d = raf.readDouble(); System.out.print(d + &quot; &quot;); } // End of “for” loop } // End of try block
  • 251. Random Access Files catch(IOException exc) { System.out.println(“Error: “ + exc.getMessage( ) ); System.out.println(&quot;Error seeking or reading.&quot;); } raf.close( ); // Close the file } // End of main ( ) } // End of class RandomAccessDemo
  • 252. Random Access Files Output from the previous Java program RandomAccessDemo: First value is 19.4 Second value is 10.1 Fourth value is 33.0 Here is every other value: 19.4 123.54 87.9
  • 253. Case Studies: Address Book Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First , Next , Previous , and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively.
  • 254. Parsing Text Files The StreamTokenizer class lets you take an input stream and parse it into words, which are known as tokens . The tokens are read one at a time. The following is the StreamTokenizer constructor: StreamTokenizer st = StreamTokenizer(Reader is)
  • 255. StreamTokenizer Constants TT_WORD The token is a word. TT_NUMBER The token is a number. TT_EOL The end of the line has been read. TT_EOF The end of the file has been read.
  • 256. StreamTokenizer Variables int ttype (token type) Contains the current token type, which matches one of the constants listed on the preceding slide. double nval Contains the value of the current token if that token is a number. String sval Contains a string that gives the characters of the current token if that token is a word.
  • 257. StreamTokenizer Methods public int nextToken() throws IOException Parses the next token from the input stream of this StreamTokenizer . The type of the next token is returned in the ttype field. If ttype == TT_WORD , the token is stored in sval ; if ttype == TT_NUMBER , the token is stored in nval .
  • 258. Example : Demo program Using StreamTokenizer Demo: ParsingTextFile.java
  • 259. ParsingTextFile.java (Demo program) // ParsingTextFile.java: ITP 120 // Process text file using StreamTokenizer Chapter 18 I/O import java.io.*; public class ParsingTextFile { // Main method public static void main(String[] args) { // Declare file reader and writer character (2 bytes) streams FileReader frs = null; FileWriter fws = null; // Declare streamTokenizer StreamTokenizer in = null;
  • 260. ParsingTextFile.java (Demo) // Declare a print stream PrintWriter out = null; // For input file fields: student name, midterm1, // midterm2, and final exam score String sname = null; double midterm1 = 0; double midterm2 = 0; double finalScore = 0; // Computed total score double total = 0; try { // Create file input and output streams frs = new FileReader(&quot;grades.dat&quot;); fws = new FileWriter(&quot;gradesout.dat&quot;);
  • 261. ParsingTextFile.java (Demo) // Create a stream tokenizer wrapping file input stream in = new StreamTokenizer(frs); out = new PrintWriter(fws); // Create PrintWriter object // Read first token in.nextToken(); // Process a record // TTs are Tokenizer constants while (in.ttype != in.TT_EOF) // TT_EOF means end of file { // Get student name if (in.ttype == in.TT_WORD) // TT_WORD means token is a word sname = in.sval; else System.out.println(&quot;Bad file format&quot;);
  • 262. ParsingTextFile.java (Demo) // Get midterm1 if (in.nextToken() == in.TT_NUMBER) //TT_NUMBER means token is a number midterm1 = in.nval; else System.out.println(&quot;Bad file format&quot;); // Get midterm2 score if (in.nextToken() == in.TT_NUMBER) midterm2 = in.nval; else System.out.println(&quot;Bad file format&quot;); // Get final exam score if (in.nextToken() == in.TT_NUMBER) finalScore = in.nval;
  • 263. ParsingTextFile.java (Demo) total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4; out.println(sname + &quot; &quot; + total); in.nextToken( ); } } catch (FileNotFoundException ex) { System.out.println(&quot;Error: &quot; + ex.getMessage()); System.out.println(&quot;File not found: in.dat&quot;); } catch (IOException ex) { System.out.println(ex.getMessage()); }
  • 264. ParsingTextFile.java (Demo) finally // Always execute finally block { try { if (frs != null) frs.close(); if (fws != null) fws.close(); } catch (IOException ex) { System.out.println(ex); } } System.out.println(&quot;To view input file, TYPE GRADES.DAT&quot;); System.out.println(&quot;To view output file, TYPE GRADESOUT.DAT&quot;); } // End of main method } // End of class
  • 265. Chapter 18 Demo Programs ReadBytes.java WriteDemo.java ShowFile.java CopyFile.java CopyFileUsingByteStream.java CompFile.java RWData.java RandomAccessDemo.java PrintWriterDemo.java ReadChars.java ReadLines.java
  • 266. Chapter 18 Demo Programs TestDataStreams.java TestFileClass.java TestPrintWriters.java ViewFile.java (cute file viewer program) ParsingTextFile.java TestRandomAccessFile.java needs these class files: AddressBook.java FixedLengthStringIO.class
  • 267. Chapter 18 Demo Programs TestDataStream.java TestFileClass.java TestFileReader.java TestFileStream.java TestFileWriter.java TestObjectStreamForArray.java TestObjectInputStream.java TestObjectOutputStream.java AddressBook.java (with FixedLengthStringIO.java) Other created or required files: object.dat, temp.txt, student.dat