Chapter 19  Binary Input & Output   Java I  ITP 120
Chapter  Objectives <ul><li>To understand how I/O is handled in Java  </li></ul><ul><li>To distinguish between text I/O an...
Overview <ul><li>The  java.io.*  package provides a library of classes to read and write various  types of data. </li></ul...
Overview  ---  Streams <ul><li>A  stream  is an abstraction of a  continuous  one-way flow of data .  </li></ul>
2 Types of Stream Classes:  Bytes & Characters <ul><li>The stream classes can be categorized into two types:  byte streams...
Byte Stream Classes  (note: the word “stream” )
Character Stream Classes  (Character = 2 bytes)
How is I/O Handled in Java? <ul><li>A  File  object encapsulates the properties of a file or a path, but does not contain ...
Text Files vs. Binary Files <ul><li>Data stored in a text file are represented in human-readable form. Data stored in a bi...
Binary I/O <ul><li>Text I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when wr...
Binary I/O Classes
<ul><li>The value returned is a byte as an int type. </li></ul>InputStream
<ul><li>The value is a byte as an int type. </li></ul>OutputStream
FileInputStream/FileOutputStream <ul><li>FileInputStream/FileOutputStream associates a binary input/output stream with an ...
FileInputStream <ul><li>To construct a FileInputStream, use the following constructors: </li></ul><ul><ul><li>public FileI...
FileOutputStream <ul><li>To construct a FileOutputStream, use the following constructors: </li></ul><ul><ul><li>public Fil...
FilterInputStream/FilterOutputStream <ul><li>Filter streams  are streams that filter bytes for some purpose. The basic byt...
DataInputStream/DataOutputStream <ul><li>DataInputStream  reads bytes from the stream and converts them into appropriate p...
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   <ul><li>A Unicode consists of two bytes. The  writeChar(char c)  method writes the ...
Using  DataInputStream / DataOutputStream   <ul><li>Data streams are used as wrappers on existing input and output streams...
Checking End of File <ul><li>TIP: If you keep reading data at the end of a stream, an  EOFException  would occur. So how d...
BufferedInputStream/ BufferedOutputStream <ul><li>Using buffers to speed up I/O  </li></ul>BufferedInputStream / BufferedO...
Constructing  BufferedInputStream / BufferedOutputStream   <ul><ul><li>// Create a BufferedInputStream </li></ul></ul><ul>...
Case Studies: Copy File  <ul><ul><li>This case study develops a program that copies files. The user needs to provide a sou...
Object I/O <ul><li>DataInputStream / DataOutputStream  enables you to perform I/O for primitive type values and strings.  ...
ObjectInputStream <ul><li>ObjectInputStream  extends  InputStream  and implements  ObjectInput  and  ObjectStreamConstants...
ObjectOutputStream <ul><li>ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants. ...
Using Object Streams <ul><li>You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using th...
Random Access Files <ul><li>All of the streams you have used so far are known as  read-only  or  write-only  streams. The ...
RandomAccessFile
File Pointer <ul><li>A random access file consists of a sequence of bytes. There is a special marker called  file pointer ...
RandomAccessFile  Methods <ul><li>Many methods in  RandomAccessFile  are the same as those in  DataInputStream  and  DataO...
RandomAccessFile  Methods, cont. <ul><li>void seek(long pos) throws IOException; </li></ul><ul><li>Sets the offset from th...
RandomAccessFile  Methods, cont. <ul><li>long length()IOException </li></ul><ul><li>Returns the length of the file. </li><...
RandomAccessFile  Constructor <ul><li>RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;rw&quot;); /...
Case Studies: Address Book <ul><li>Now let us use  RandomAccessFile  to create a useful project for storing and viewing an...
Fixed Length String I/O <ul><li>Random access files are often used to process files of records. For convenience, fixed-len...
End of Presentation Binary Input & Output   Chapter 18
How is I/O Handled in Java? <ul><li>A  File  object encapsulates the properties of a file or a path, but does not contain ...
Text Files vs. Binary Files <ul><li>Data stored in a text file are represented in human-readable form. Data stored in a bi...
Binary File I/O <ul><li>Text I/O requires encoding and decoding.  The JVM converts a Unicode char to a file-specific encod...
Binary I/O Classes  Inheritance Hierarchy
<ul><li>The value returned is a byte as an int type. </li></ul>InputStream (a byte stream class)
<ul><li>The value is a byte as an int type. </li></ul>OutputStream ( a byte stream class)
FileInputStream & FileOutputStream (byte streams) <ul><li>FileInputStream/FileOutputStream associates a binary input/outpu...
FileInputStream (byte stream) <ul><li>To construct a FileInputStream, use the following constructors: </li></ul><ul><ul><l...
FileOutputStream (byte stream) <ul><li>To construct a FileOutputStream, use the following constructors: </li></ul><ul><ul>...
FilterInputStream/FilterOutputStream <ul><li>Filter streams  are streams that filter bytes for some purpose. The basic byt...
DataInputStream & DataOutputStream (byte streams) <ul><li>DataInputStream  reads bytes from the stream and converts them i...
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   <ul><li>A Unicode char is 2 bytes. The  writeChar(char ch)  method writes the Unico...
Using  DataInputStream / DataOutputStream   <ul><li>Data streams are used as wrappers on existing input and output streams...
Checking for the End of File (EOF) <ul><li>TIP: If the program tried to read data at the end of a stream, an  EOFException...
BufferedInputStream/ BufferedOutputStream <ul><li>Use buffers to speed up I/O processes </li></ul>BufferedInputStream / Bu...
Constructing  BufferedInputStream / BufferedOutputStream   <ul><ul><li>// Create a BufferedInputStream </li></ul></ul><ul>...
CopyFile.java <ul><ul><li>CopyFile.java is  a program that copies files. The user needs to provide a source file and a tar...
Object I/O  (optional) <ul><li>DataInputStream / DataOutputStream  enables you to perform I/O for primitive type values an...
ObjectInputStream (optional) <ul><li>ObjectInputStream  extends  InputStream  and implements  ObjectInput  and  ObjectStre...
ObjectOutputStream (optional) <ul><li>ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStream...
Using Object Streams (optional) <ul><li>You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStre...
The  Serializable  Interface <ul><li>Not all objects can be written to an output stream. Objects that  CAN  be written to ...
The  transient  Keyword <ul><li>If an object is an instance of  Serializable , but it contains  non-serializable instance ...
The  transient  Keyword, cont. <ul><li>Consider the following class: </li></ul><ul><li>  </li></ul><ul><li>public class IT...
Serializing Arrays (optional)   <ul><li>An array is serializable if all its elements are serializable. So an entire array ...
Random Access Files <ul><li>All of the streams you have used so far are known as  read-only  or  write-only  streams. The ...
RandomAccessFile
File Pointers <ul><li>A random access file consists of a sequence of bytes. There is a special marker called  file pointer...
File Pointers  (moving the pointer 4 bytes ahead)
RandomAccessFile   Methods <ul><li>Many methods in  RandomAccessFile  are the same as those in  </li></ul><ul><li>DataInpu...
RandomAccessFile   Methods, cont. <ul><li>void seek(long pos) throws IOException; </li></ul><ul><li>Sets the offset from t...
RandomAccessFile   Methods, cont. <ul><li>long length()IOException </li></ul><ul><li>Returns the length of the file. </li>...
RandomAccessFile  Constructors <ul><li>RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;rw&quot;); ...
Case Study: Address Book <ul><li>Now let us use  RandomAccessFile  to create a useful project for storing and viewing and ...
Fixed Length String I/O <ul><li>Random access files are often used to process files of records. For convenience, fixed-len...
Chapter 18 Demo Programs <ul><li>ReadBytes.java (skip)  WriteData.java </li></ul><ul><li>WriteDemo.java  ReadData.java </l...
Chapter 18 Demo Programs <ul><li>TextFileScannerDemo.java  </li></ul><ul><ul><li>Uses input file  morestuff.txt   </li></u...
Chapter 18 Demo Programs <ul><li>TestDataStreams.java </li></ul><ul><li>TestFileClass.java </li></ul><ul><li>TestPrintWrit...
Chapter 18  Demo Programs <ul><li>TestDataStream.java </li></ul><ul><li>TestFileReader.java  (needs temp.txt) </li></ul><u...
Chapter 18  Input / Output  Optional: More on Java File I/O   Chapter 18  Java I  ITP 120
Chapter 18:  More on Input and Output  <ul><ul><li>Stream Classes  (byte & character streams) </li></ul></ul><ul><ul><li>P...
Chapter 18  Input /Output  Objectives <ul><li>Understand input & output streams and learn how to create them. </li></ul><u...
Overview <ul><li>The  java.io.*  package provides a library of classes to read and write various  types of data. </li></ul...
Overview  Streams <ul><li>In Java, all  Input/Output   is handled by  streams </li></ul><ul><li>A stream is an abstraction...
Overview  ---  Streams <ul><li>A  stream  is an abstraction of a  continuous  one-way flow of data .  </li></ul>
Overview and Background <ul><li>The  original  version of Java defined  only the byte   stream , but  character streams  w...
How is I/O Handled in Java? <ul><li>A  File  object encapsulates the properties of a file or a path, but does not contain ...
Text Files vs. Binary Files <ul><li>Data stored in a text file are represented in human-readable form. Data stored in a bi...
Binary I/O <ul><li>Text I/O requires encoding and decoding. The JVM converts a Unicode character to  file-specific encodin...
2 Types of Stream Classes:  Bytes & Characters <ul><li>The stream classes can be categorized into two types:  byte streams...
Byte Stream Classes  (note: “stream” )
Character Stream Classes  (Character = 2 bytes)
Predefined Streams in Java <ul><li>All Java programs automatically import the  java.lang  package. </li></ul><ul><li>The  ...
Predefined Streams in Java:  System class <ul><li>System.in  refers to the standard  input  stream which is the keyboard b...
Predefined Streams in Java:  System class <ul><li>System.in  is an object of type InputStream.  (byte stream) </li></ul><u...
Reading Keyboard Input <ul><li>// Read an array of bytes from the keyboard.  </li></ul><ul><li>import java.io.*;  </li></u...
Reading Keyboard Input  <ul><li>Here is a sample run from the  previous  program: </li></ul><ul><li>Enter some characters:...
Writing Output to the Monitor <ul><li>// Demonstrate System.out.write().  Java program  WriteDemo.java </li></ul><ul><li>p...
Stream classes  (Bytes & Characters) <ul><li>The  java.io  package provides two categories of classes: </li></ul><ul><ul><...
Stream Classes <ul><li>FileInputStream  can read raw streams of data from files. </li></ul><ul><li>DataOutputStream  can w...
InputStream Class  (for reading bytes) <ul><li>The following methods are defined in InputStream  </li></ul><ul><li>and are...
InputStream Class  (for reading bytes) <ul><li>The following methods are defined in InputStream and are often useful: </li...
InputStream Class  (for reading bytes) <ul><li>The following method is defined in InputStream and is often useful: </li></...
Reading & Writing Files Using Byte Streams <ul><li>To create a byte stream linked to a file, use  FileInputStream  or  Fil...
Reading & Writing Files Using Byte Streams <ul><li>/* Display a text file.  </li></ul><ul><li>To use this program, specify...
Reading & Writing Files Using Byte Streams <ul><li>public class ShowFile {  </li></ul><ul><li>public static void main(Stri...
Reading & Writing Files Using Byte Streams <ul><li>// Read bytes until EOF is encountered  </li></ul><ul><li>do {  </li></...
Writing to a File Using Byte Streams <ul><li>/* Java program to Copy a text file.  </li></ul><ul><li>To use this program, ...
Writing to a File Using Byte Streams <ul><li>// CopyFile.java  Demo byte stream file operations </li></ul><ul><li>import j...
Writing to a File Using Byte Streams try {  // outer try block //  try to open input file  try {  // inner try fin = new F...
Writing to a File Using Byte Streams <ul><li>// open output file  </li></ul><ul><li>try {  </li></ul><ul><li>fout = new Fi...
Writing to a File Using Byte Streams <ul><li>catch(ArrayIndexOutOfBoundsException exc) {  </li></ul><ul><li>System.out.pri...
Reading & Writing Binary Data <ul><li>So far, we have been reading and writing bytes containing  ASCII  bytes. </li></ul><...
Reading & Writing Binary Data <ul><li>Note: Binary data is NOT in human-readable text format, obviously. </li></ul><ul><li...
Reading & Writing Binary Data <ul><li>The constructor for DataInputStream is: </li></ul><ul><li>DataInputStream(InputStrea...
Reading & Writing Binary Data  Examples <ul><li>To create  an input stream for the file  in.dat  ( bytes) </li></ul><ul><l...
Reading & Writing Binary Data <ul><li>Common Input Methods Defined by  DataInputStream (a byte stream) </li></ul><ul><li>I...
Reading & Writing Binary Data <ul><li>Common Output Methods Defined by  DataOutputStream ( byte stream) </li></ul><ul><li>...
Reading & Writing Binary Data <ul><li>Here is a Java program that demonstrates  DataOutputStream  and  DataInputStream .  ...
Reading & Writing Binary Data <ul><li>int i = 120;  </li></ul><ul><li>double d = 1049.56;  </li></ul><ul><li>boolean b = t...
Reading & Writing Binary Data <ul><li>try {  // Write the binary data </li></ul><ul><li>System.out.println(&quot;Writing &...
Reading & Writing Binary Data <ul><li>catch(IOException exc) {  </li></ul><ul><li>System.out.println(&quot;Write error: + ...
Reading & Writing Binary Data <ul><li>try {  // Read the binary data </li></ul><ul><li>i = dataIn.readInt();  </li></ul><u...
Reading & Writing Binary Data <ul><li>catch(IOException exc) {  </li></ul><ul><li>System.out.println(&quot;Read error.“ + ...
Reader  class methods for reading  characters <ul><li>The  Reader  class is similar to the  InputStream  class. The method...
OutputStream ( bytes) & Writer (for characters) <ul><li>Like InputStream (for reading  bytes ) and Reader (for reading  ch...
OutputStream  (Writing bytes) <ul><li>public abstract void write(int b) throws IOException </li></ul><ul><li>Write a byte ...
Writer  (Writing characters)  (Same as OutputStream) <ul><li>public abstract void write(int b) throws IOException </li></u...
Console Input using Character Streams <ul><li>For Java code that will be internationalized, inputting data from the consol...
Console Input using Character Streams <ul><li>You must first convert  the input from System.in from a byte stream into a c...
Console Input using Character Streams <ul><li>Next, using the object produced by InputStreamReader, construct  a BufferedR...
Console Input using Character Streams <ul><li>Putting it all together, the following line of code creates a  BufferReader ...
Console Input using Character Streams <ul><li>Reading Characters </li></ul><ul><li>Characters can be read from  System.in ...
Console Input using Character Streams <ul><li>int read( ) throws IOException </li></ul><ul><li>reads a single Unicode char...
Console Input using Character Streams <ul><li>The following program demonstrates the  read( )   method by reading characte...
Console Input using Character Streams <ul><li>BufferedReader br = new  </li></ul><ul><li>BufferedReader(new InputStreamRea...
Console Input using Character Streams <ul><li>Output from the previous program could be: </li></ul><ul><li>Enter some char...
Console Input using Character Streams <ul><li>Reading Character Strings from the Keyboard … </li></ul><ul><li>To read a st...
Console Input using Character Streams <ul><li>The following program demonstrates BufferedReader and the readLine() method....
Console Input using Character Streams <ul><li>System.out.println(&quot;Enter lines of text.&quot;);  </li></ul><ul><li>Sys...
Console  Output  using Character Streams <ul><li>The preferred method of writing to the console (monitor) when using Java ...
Console Output using Character Streams <ul><li>PrintWriter(OutputStream  outputStream , boolean flushOnNewline) </li></ul>...
Console Output using Character Streams <ul><li>To write to the console (monitor) using a  PrintWriter , specify  System.ou...
Console Output using Character Streams <ul><li>// Demonstrate PrintWriter.  </li></ul><ul><li>import java.io.*;  </li></ul...
Console Output using Character Streams <ul><li>pw.println(&quot;Using a PrintWriter.&quot;);  // PrintWriter Demo </li></u...
File Input & Output using Character Streams <ul><li>In general, to perform  character-based  file I/O, you will use the  F...
File I / O using Character Streams  FileWriter <ul><li>// A simple keyboard-to-disk utility that  demonstrates a FileWrite...
File I / O using Character Streams  FileWriter <ul><li>try {  </li></ul><ul><li>fw = new FileWriter(&quot;test.txt&quot;);...
File I / O using Character Streams  FileWriter <ul><li>System.out.println(&quot;Enter text ('stop' to quit).&quot;);  </li...
File I / O using Character Streams  FileReader <ul><li>The FileReader class creates a  Reader  that you can use to read th...
File I / O using Character Streams  FileReader <ul><li>The following program reads a text file called  “test.txt” and disp...
File I / O using Character Streams  FileReader <ul><li>while((s = br.readLine()) != null)  </li></ul><ul><li>{  </li></ul>...
The File Class: Objectives <ul><ul><li>To discover file properties, delete and rename files using the  File  class  </li><...
The File Class <ul><li>The  File  class is intended to provide an abstraction that deals with most of the machine-dependen...
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 pl...
The File Class and Processing External Files <ul><li>The  File class  provides an abstraction that deals with most of the ...
The File Class and Processing External Files <ul><li>You can use the  getName( )  method to get the name of the file. </li...
The File Class and Processing External Files <ul><li>You can use the  getPath( )  method to get the full path of the file ...
Demo Program:  TestFileClass.java <ul><li>// TestFileClass.java: Demonstrate the File class  Chapt 18 I/O  ITP120 </li></u...
Demo Program:  TestFileClass.java <ul><li>try { </li></ul><ul><li>System.out.println(&quot;What is its canonical path? &qu...
Processing External Files <ul><li>Again, you must use  file streams  to read from or write to a disk file.  </li></ul><ul>...
File I/O Stream Constructors <ul><li>To create a file stream, use these constructors: </li></ul><ul><li>public FileInputSt...
File I/O Stream Constructors <ul><li>Constructing instances of  FileInputStream ,  FileOutputStream ,  FileReader , and  F...
Demo Program:  TestFileReader.java <ul><li>// TestFileReader.java  Chapter 18  I/O  ITP 120 </li></ul><ul><li>import java....
Demo Program:  TestFileReader.java <ul><li>System.out.println(&quot;File temp.txt does not exist&quot;); </li></ul><ul><li...
Demo Program: TestFileWriter.java <ul><li>// TestFileWriter.java  Chapter 18  File I/O  ITP 120 </li></ul><ul><li>import j...
Processing External Files
Processing External Files <ul><li>The previous diagram shows that: </li></ul><ul><li>FileInputStream, fis, is used to read...
Processing External Files  <ul><li>// CopyFileUsingByteStream.java  For  Copying  files  (byte streams) </li></ul><ul><li>...
Processing External Files  if (args.length !=2)  // args[0] is source file {    // args[1]  is target file System.out.prin...
Processing External Files  <ul><li>try </li></ul><ul><li>{  </li></ul><ul><li>// Create file input stream </li></ul><ul><l...
Processing External Files <ul><li>else </li></ul><ul><li>fos = new FileOutputStream(args[1]);  // FileOutputStream </li></...
Processing External Files  <ul><li>// Continuously read a byte from fis and write it to fos </li></ul><ul><li>int r; </li>...
Processing External Files <ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Some IO...
Processing External Files <ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>...
Filter Streams <ul><li>Filter streams  are streams that filter bytes or characters for some purpose. </li></ul><ul><li>If ...
Filter Streams <ul><li>To process  strings ,  use  BufferedReader  and  PushbackReader  to filter characters. </li></ul><u...
FilterInputStream  subclasses <ul><li>DataInputStream   handles  binary  formats for all primitive data types. </li></ul><...
FilterOutputStream  subclasses <ul><li>DataOutputStream   outputs the  binary  formats for all primitive data types which ...
Data Streams  (bytes) <ul><li>The data streams ( DataInputStream  and  DataOutputStream ) </li></ul><ul><li>read and write...
DataInputStream Methods defined in the DataInput Interface <ul><li>int readByte() throws IOException </li></ul><ul><li>int...
DataOutputStream Methods   defined in the DataOutput   interface   <ul><li>void writeByte(byte b) throws IOException  </li...
DataInputStream & DataOutput Stream  Constructors <ul><li>Data streams are used as wrappers on existing input and output s...
Using Data Streams  <ul><li>The next  example shows a program that: </li></ul><ul><li>Creates 10 random integers,  </li></...
Using Data Streams  Demo  Example  <ul><li>// TestDataStreams.java: Create a file, store it in binary form, and </li></ul>...
Using Data Streams  Demo  Example  <ul><li>// Construct a temp file </li></ul><ul><li>File tempFile = new File(&quot;mytem...
Using Data Streams  Demo Example <ul><li>// Write data </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Crea...
Using Data Streams  Demo  Example  <ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println...
Using Data Streams  Demo  Example  <ul><li>// Read data </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Cre...
Using Data Streams  <ul><li>catch (FileNotFoundException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quo...
Using Data Streams  <ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>if (di...
Using Data Streams  Demo  Example  <ul><li>The previous Java program  TestDataStreams.java  creates a  DataInputStream  ob...
Character Classes  <ul><li>The classes that handle characters have at the top of their hierarchy,  Reader  and  Writer </l...
File Class <ul><li>File class provides functionality for working directly with files in the operating system </li></ul><ul...
File Class <ul><li>Example:  DirectoryContents.java  listing the contents of a directory using File class </li></ul><ul><l...
Using Java I/O <ul><li>Many of the methods including constructors of Java.io classes throw exceptions:  </li></ul><ul><li>...
Using Java I/O <ul><li>Example  Reading strings from the keyboard </li></ul><ul><li>Import java.io.* </li></ul><ul><li>pub...
Using Java I/O <ul><li>Example:  Reading from an external file </li></ul><ul><li>public class ReadFromFile { </li></ul><ul...
Using Java I/O <ul><li>Example  Continued </li></ul><ul><li>// Now let us start reading from the opened file </li></ul><ul...
Using Java I/O <ul><li>Example  continued </li></ul><ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>if( br  != null)...
Print Streams <ul><li>The data output stream outputs a  binary representation  of data, so you cannot view its contents as...
Print Streams:   PrintWriter  Constructors <ul><li>PrintWriter(Writer out) </li></ul><ul><li>PrintWriter(Writer out, boole...
Print Streams:  PrintWriter   Methods  (for chars) <ul><li>void print(Object o) </li></ul><ul><li>void print(String s) </l...
Print Streams:  PrintWriter  Methods <ul><li>Note: </li></ul><ul><li>On the previous slide, you may replace  print  with  ...
Demo Program Example Using Print Streams <ul><li>The next sample Java program creates a print stream,  pw , of  PrintWrite...
Using Pri
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
Upcoming SlideShare
Loading in...5
×

Itp 120 Chapt 19 2009 Binary Input & Output

3,179

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,179
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
189
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Itp 120 Chapt 19 2009 Binary Input & Output

  1. 1. Chapter 19 Binary Input & Output Java I ITP 120
  2. 2. Chapter Objectives <ul><li>To understand how I/O is handled in Java </li></ul><ul><li>To distinguish between text I/O and binary I/O </li></ul><ul><li>To read and write bytes using FileInputStream and FileOutputStream </li></ul><ul><li>To read and write primitive values and strings using the DataInputStream and DataOutputStream classes </li></ul><ul><li>To store and restore objects using ObjectOutputStream and ObjectInputStream , and to understand how objects are serialized and what kind of objects can be serialized </li></ul><ul><li>To use the Serializable interface to enable objects to be serializable (optional) </li></ul><ul><li>To know how to serialize arrays (optional) </li></ul><ul><li>To use RandomAccessFile for both read and write (Optional). </li></ul>
  3. 3. Overview <ul><li>The java.io.* package provides a library of classes to read and write various types of data. </li></ul><ul><li>In Java, all data I/O is handled in the form of streams </li></ul><ul><li>Data streams can be byte streams or character streams </li></ul><ul><li>The java.io package has classes that process byte streams of all types </li></ul><ul><li>NOTE: In Java, a character is 2 BYTES ! </li></ul><ul><li>Also NOTE: a Unicode character is 2 bytes ! </li></ul><ul><li>The Reader and Writer classes process character streams. </li></ul><ul><li>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 . </li></ul>
  4. 4. Overview --- Streams <ul><li>A stream is an abstraction of a continuous one-way flow of data . </li></ul>
  5. 5. 2 Types of Stream Classes: Bytes & Characters <ul><li>The stream classes can be categorized into two types: byte streams and character streams . </li></ul><ul><li>The InputStream/OutputStream class is the root of all BYTE stream classes </li></ul><ul><li>The Reader/Writer class is the root of all CHARACTER stream classes. </li></ul><ul><li>The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer . </li></ul>
  6. 6. Byte Stream Classes (note: the word “stream” )
  7. 7. Character Stream Classes (Character = 2 bytes)
  8. 8. How is I/O Handled in Java? <ul><li>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. </li></ul>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. 9. Text Files vs. Binary Files <ul><li>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. </li></ul><ul><li>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 . </li></ul>
  10. 10. Binary I/O <ul><li>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. </li></ul>
  11. 11. Binary I/O Classes
  12. 12. <ul><li>The value returned is a byte as an int type. </li></ul>InputStream
  13. 13. <ul><li>The value is a byte as an int type. </li></ul>OutputStream
  14. 14. FileInputStream/FileOutputStream <ul><li>FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses. </li></ul>
  15. 15. FileInputStream <ul><li>To construct a FileInputStream, use the following constructors: </li></ul><ul><ul><li>public FileInputStream(String filename) </li></ul></ul><ul><ul><li>public FileInputStream(File file) </li></ul></ul><ul><ul><li>A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file. </li></ul></ul>
  16. 16. FileOutputStream <ul><li>To construct a FileOutputStream, use the following constructors: </li></ul><ul><ul><li>public FileOutputStream(String filename) </li></ul></ul><ul><ul><li>public FileOutputStream(File file) </li></ul></ul><ul><ul><li>public FileOutputStream(String filename, boolean append) </li></ul></ul><ul><ul><li>public FileOutputStream(File file, boolean append) </li></ul></ul><ul><li>   </li></ul><ul><li>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. </li></ul>TestFileStream Run
  17. 17. FilterInputStream/FilterOutputStream <ul><li>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. </li></ul>
  18. 18. DataInputStream/DataOutputStream <ul><li>DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. </li></ul>DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.
  19. 19. DataInputStream DataInputStream extends FilterInputStream and implements the DataInput interface.
  20. 20. DataOutputStream DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
  21. 21. Characters and Strings in Binary I/O <ul><li>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. </li></ul>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. 22. Using DataInputStream / DataOutputStream <ul><li>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: </li></ul><ul><ul><li>public DataInputStream(InputStream instream) </li></ul></ul><ul><ul><li>public DataOutputStream(OutputStream outstream) </li></ul></ul><ul><li>  </li></ul><ul><li>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 . </li></ul><ul><ul><li>DataInputStream infile = </li></ul></ul><ul><ul><li>new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); </li></ul></ul><ul><ul><li>DataOutputStream outfile = </li></ul></ul><ul><ul><li>new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); </li></ul></ul>TestDataStream Run
  23. 23. Checking End of File <ul><li>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. </li></ul>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. 24. BufferedInputStream/ BufferedOutputStream <ul><li>Using buffers to speed up I/O </li></ul>BufferedInputStream / BufferedOutputStream does not contain new methods. All the methods BufferedInputStream / BufferedOutputStream are inherited from the InputStream / OutputStream classes.
  25. 25. Constructing BufferedInputStream / BufferedOutputStream <ul><ul><li>// Create a BufferedInputStream </li></ul></ul><ul><ul><li>public BufferedInputStream(InputStream in) </li></ul></ul><ul><ul><li>public BufferedInputStream(InputStream in, int bufferSize) </li></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>// Create a BufferedOutputStream </li></ul></ul><ul><ul><li>public BufferedOutputStream(OutputStream out) </li></ul></ul><ul><ul><li>public BufferedOutputStream(OutputStreamr out, int bufferSize) </li></ul></ul>
  26. 26. Case Studies: Copy File <ul><ul><li>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: </li></ul></ul><ul><ul><ul><li>java Copy source target </li></ul></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>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. </li></ul></ul>Copy Run
  27. 27. Object I/O <ul><li>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. </li></ul>Optional
  28. 28. ObjectInputStream <ul><li>ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants . </li></ul>
  29. 29. ObjectOutputStream <ul><li>ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants. </li></ul>
  30. 30. Using Object Streams <ul><li>You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: </li></ul><ul><ul><li>// Create an ObjectInputStream </li></ul></ul><ul><ul><li>public ObjectInputStream(InputStream in) </li></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>// Create an ObjectOutputStream </li></ul></ul><ul><ul><li>public ObjectOutputStream(OutputStream out) </li></ul></ul>TestObjectOutputStream Run TestObjectInputStream Run
  31. 31. Random Access Files <ul><li>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. </li></ul>
  32. 32. RandomAccessFile
  33. 33. File Pointer <ul><li>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. </li></ul>
  34. 34. RandomAccessFile Methods <ul><li>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. </li></ul>
  35. 35. RandomAccessFile Methods, cont. <ul><li>void seek(long pos) throws IOException; </li></ul><ul><li>Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs. </li></ul><ul><li>long getFilePointer() IOException; </li></ul><ul><li>Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs. </li></ul>
  36. 36. RandomAccessFile Methods, cont. <ul><li>long length()IOException </li></ul><ul><li>Returns the length of the file. </li></ul><ul><li>final void writeChar(int v) throws IOException </li></ul><ul><li>Writes a character to the file as a two-byte Unicode, with the high byte written first. </li></ul><ul><li>final void writeChars(String s) throws IOException </li></ul><ul><li>Writes a string to the file as a sequence of characters. </li></ul>
  37. 37. RandomAccessFile Constructor <ul><li>RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;rw&quot;); //allows read and write </li></ul><ul><li>RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;r&quot;); //read only </li></ul>
  38. 38. Case Studies: Address Book <ul><li>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. </li></ul>Optional
  39. 39. Fixed Length String I/O <ul><li>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. </li></ul>FixedLengthStringIO
  40. 40. End of Presentation Binary Input & Output Chapter 18
  41. 41. How is I/O Handled in Java? <ul><li>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. </li></ul>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. 42. Text Files vs. Binary Files <ul><li>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. </li></ul><ul><li>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 .) </li></ul>
  43. 43. Binary File I/O <ul><li>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. </li></ul>
  44. 44. Binary I/O Classes Inheritance Hierarchy
  45. 45. <ul><li>The value returned is a byte as an int type. </li></ul>InputStream (a byte stream class)
  46. 46. <ul><li>The value is a byte as an int type. </li></ul>OutputStream ( a byte stream class)
  47. 47. FileInputStream & FileOutputStream (byte streams) <ul><li>FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses. </li></ul>
  48. 48. FileInputStream (byte stream) <ul><li>To construct a FileInputStream, use the following constructors: </li></ul><ul><ul><li>public FileInputStream(String filename) </li></ul></ul><ul><ul><li>public FileInputStream(File file) </li></ul></ul><ul><ul><li>A java.io.FileNotFoundException would occur if you attempt </li></ul></ul><ul><ul><li>to create a FileInputStream with a nonexistent file. </li></ul></ul>
  49. 49. FileOutputStream (byte stream) <ul><li>To construct a FileOutputStream, use the following constructors: </li></ul><ul><ul><li>public FileOutputStream(String filename) </li></ul></ul><ul><ul><li>public FileOutputStream(File file) </li></ul></ul><ul><ul><li>public FileOutputStream(String filename, boolean append) </li></ul></ul><ul><ul><li>public FileOutputStream(File file, boolean append) // append = true to add on to the file </li></ul></ul><ul><li>   </li></ul><ul><li>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. </li></ul><ul><li>Demo Program: TestFileStream.java </li></ul>
  50. 50. FilterInputStream/FilterOutputStream <ul><li>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. </li></ul>
  51. 51. DataInputStream & DataOutputStream (byte streams) <ul><li>DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. </li></ul>DataOutputStream converts primitive type values or strings into bytes and outputs the bytes to the stream.
  52. 52. DataInputStream ( byte stream) DataInputStream extends FilterInputStream and implements the DataInput interface.
  53. 53. DataOutputStream (byte stream) DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
  54. 54. Characters and Strings in Binary I/O <ul><li>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. </li></ul>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. 55. Using DataInputStream / DataOutputStream <ul><li>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: </li></ul><ul><ul><li>public DataInputStream(InputStream instream) </li></ul></ul><ul><ul><li>public DataOutputStream(OutputStream outstream)   </li></ul></ul><ul><li>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 . </li></ul><ul><ul><li>DataInputStream infile = </li></ul></ul><ul><ul><li>new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); </li></ul></ul><ul><ul><li>DataOutputStream outfile = </li></ul></ul><ul><ul><li>new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); </li></ul></ul><ul><ul><li>Demo Program: TestDataStream.java </li></ul></ul>
  56. 56. Checking for the End of File (EOF) <ul><li>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) </li></ul>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. 57. BufferedInputStream/ BufferedOutputStream <ul><li>Use buffers to speed up I/O processes </li></ul>BufferedInputStream / BufferedOutputStream does not contain new methods. All the methods BufferedInputStream / BufferedOutputStream are inherited from the InputStream / OutputStream classes.
  58. 58. Constructing BufferedInputStream / BufferedOutputStream <ul><ul><li>// Create a BufferedInputStream </li></ul></ul><ul><ul><li>public BufferedInputStream(InputStream in) </li></ul></ul><ul><ul><li>public BufferedInputStream(InputStream in, int bufferSize) </li></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>// Create a BufferedOutputStream </li></ul></ul><ul><ul><li>public BufferedOutputStream(OutputStream out) </li></ul></ul><ul><ul><li>public BufferedOutputStream(OutputStream out, int bufferSize) </li></ul></ul>
  59. 59. CopyFile.java <ul><ul><li>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: </li></ul></ul><ul><ul><ul><li>java CopyFile source target </li></ul></ul></ul><ul><ul><ul><li>Also: java CompFile source target </li></ul></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>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. </li></ul></ul>
  60. 60. Object I/O (optional) <ul><li>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. </li></ul>
  61. 61. ObjectInputStream (optional) <ul><li>ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants . </li></ul>
  62. 62. ObjectOutputStream (optional) <ul><li>ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants. </li></ul>
  63. 63. Using Object Streams (optional) <ul><li>You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: </li></ul><ul><ul><li>// Create an ObjectInputStream </li></ul></ul><ul><ul><li>public ObjectInputStream(InputStream in) </li></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>// Create an ObjectOutputStream </li></ul></ul><ul><ul><li>public ObjectOutputStream(OutputStream out) </li></ul></ul><ul><ul><li>Demo: TestObjectOutputStream.java </li></ul></ul><ul><ul><li>TestObjectInputStream.java </li></ul></ul>
  64. 64. The Serializable Interface <ul><li>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. </li></ul><ul><li>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 . </li></ul><ul><li>Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays. </li></ul>
  65. 65. The transient Keyword <ul><li>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 ! </li></ul><ul><li>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. </li></ul>
  66. 66. The transient Keyword, cont. <ul><li>Consider the following class: </li></ul><ul><li>  </li></ul><ul><li>public class ITP120 implements java.io.Serializable { </li></ul><ul><li>private int v1; </li></ul><ul><li>private static double v2; </li></ul><ul><li>private transient A v3 = new A(); </li></ul><ul><li>} </li></ul><ul><li>class A { } // A is not serializable </li></ul><ul><li>  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. </li></ul>
  67. 67. Serializing Arrays (optional) <ul><li>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 . </li></ul><ul><li>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. </li></ul><ul><li>Demo Program: TestObjectStreamForArray.java </li></ul>
  68. 68. Random Access Files <ul><li>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. </li></ul><ul><li>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. </li></ul>
  69. 69. RandomAccessFile
  70. 70. File Pointers <ul><li>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. </li></ul>
  71. 71. File Pointers (moving the pointer 4 bytes ahead)
  72. 72. RandomAccessFile Methods <ul><li>Many methods in RandomAccessFile are the same as those in </li></ul><ul><li>DataInputStream and DataOutputStream . </li></ul><ul><li>For example, readInt() , readLong() , writeDouble() , readLine() , writeInt() , and writeLong() </li></ul><ul><li>can be used in data input stream or data output stream as well as in RandomAccessFile streams. </li></ul>
  73. 73. RandomAccessFile Methods, cont. <ul><li>void seek(long pos) throws IOException; </li></ul><ul><li>Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs. </li></ul><ul><li>long getFilePointer() IOException; </li></ul><ul><li>Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs. </li></ul>
  74. 74. RandomAccessFile Methods, cont. <ul><li>long length()IOException </li></ul><ul><li>Returns the length of the file. </li></ul><ul><li>final void writeChar(int v) throws IOException </li></ul><ul><li>Writes a character to the file as a two-byte Unicode, with the high byte written first. </li></ul><ul><li>final void writeChars(String s) throws IOException </li></ul><ul><li>Writes a string to the file as a sequence of characters. </li></ul>
  75. 75. RandomAccessFile Constructors <ul><li>RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;rw&quot;); //allows read and write to the file </li></ul><ul><li>RandomAccessFile raf = new RandomAccessFile(&quot;test.dat&quot;, &quot;r&quot;); //read only </li></ul><ul><li>Demo program: TestRandomAccessFile.java </li></ul><ul><li>(uses FixedLengthStringIO.java) </li></ul>
  76. 76. Case Study: Address Book <ul><li>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. </li></ul><ul><li>Run: AddressBook.java which uses FixedLengthStringIO.java </li></ul>
  77. 77. Fixed Length String I/O <ul><li>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. </li></ul>FixedLengthStringIO
  78. 78. Chapter 18 Demo Programs <ul><li>ReadBytes.java (skip) WriteData.java </li></ul><ul><li>WriteDemo.java ReadData.java </li></ul><ul><li>ShowFile.java </li></ul><ul><li>CopyFile.java CopyFileUsingByteStream.java </li></ul><ul><li>CompFile.java </li></ul><ul><li>RWData.java </li></ul><ul><li>RandomAccessDemo.java </li></ul><ul><li>PrintWriterDemo.java </li></ul><ul><li>ReadChars.java or BuffReader.java </li></ul><ul><li>ReadLines.java (BufferedReader) </li></ul>
  79. 79. Chapter 18 Demo Programs <ul><li>TextFileScannerDemo.java </li></ul><ul><ul><li>Uses input file morestuff.txt </li></ul></ul><ul><li>HasNextLineDemo.java </li></ul><ul><ul><li>Uses input file original.txt </li></ul></ul><ul><ul><li>and creates output file numbered.txt </li></ul></ul><ul><li>BufferReaderDemo.java </li></ul><ul><ul><li>Uses input file: buffer.txt </li></ul></ul>
  80. 80. Chapter 18 Demo Programs <ul><li>TestDataStreams.java </li></ul><ul><li>TestFileClass.java </li></ul><ul><li>TestPrintWriters.java </li></ul><ul><li>ViewFile.java (GUI text file viewer program) </li></ul><ul><li>needs MyFrameWithExitHanding.java class file </li></ul><ul><li>ParsingTextFile.java (needs grades.dat file) </li></ul><ul><li>(creates gradesout.dat) </li></ul><ul><li>TestRandomAccessFile.java </li></ul><ul><li>AddressBook.java (creates file address.dat) </li></ul><ul><ul><li>needs FixedLengthStringIO.class file </li></ul></ul>
  81. 81. Chapter 18 Demo Programs <ul><li>TestDataStream.java </li></ul><ul><li>TestFileReader.java (needs temp.txt) </li></ul><ul><li>TestFileStream.java </li></ul><ul><li>TestFileWriter.java (needs testdata.txt) </li></ul><ul><li>TestObjectStreamForArray.java ( creates array.dat) </li></ul><ul><li>TestObjectOutputStream.java </li></ul><ul><li>(creates object.dat) </li></ul><ul><li>TestObjectInputStream.java (reads object.dat) </li></ul>
  82. 82. Chapter 18 Input / Output Optional: More on Java File I/O Chapter 18 Java I ITP 120
  83. 83. Chapter 18: More on Input and Output <ul><ul><li>Stream Classes (byte & character streams) </li></ul></ul><ul><ul><li>Predefined Streams (System.in, System.out, System.err) </li></ul></ul><ul><ul><li>Processing External Files </li></ul></ul><ul><ul><li>Data Streams </li></ul></ul><ul><ul><li>Print Streams </li></ul></ul><ul><ul><li>Buffered Streams </li></ul></ul><ul><ul><li>Text Input and Output on the Console </li></ul></ul><ul><ul><li>Random Access Files </li></ul></ul>
  84. 84. Chapter 18 Input /Output Objectives <ul><li>Understand input & output streams and learn how to create them. </li></ul><ul><li>Discover the uses of byte and character streams. </li></ul><ul><li>To know how to read from / write to external files using file streams. </li></ul><ul><li>To become familiar with the File class. </li></ul><ul><li>To use print streams to output data of primitive types in text format. </li></ul><ul><li>To know how to read and write text data files . </li></ul><ul><li>Use text input and output on the console. </li></ul><ul><li>Use RandomAccessFile for reading & writing random access files. </li></ul>
  85. 85. Overview <ul><li>The java.io.* package provides a library of classes to read and write various types of data. </li></ul><ul><li>In Java, all data I/O is handled in the form of streams </li></ul><ul><li>Data streams can be byte streams or character streams </li></ul><ul><li>The java.io package has classes that process byte streams of all types </li></ul><ul><li>NOTE: In Java, a character is 2 BYTES ! </li></ul><ul><li>NOTE: Unicode character is 2 bytes ! </li></ul><ul><li>The Reader and Writer classes process character streams. </li></ul><ul><li>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 . </li></ul>
  86. 86. Overview Streams <ul><li>In Java, all Input/Output is handled by streams </li></ul><ul><li>A stream is an abstraction of the continuous one-way flow of data </li></ul><ul><li>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. </li></ul><ul><li>All streams EXCEPT random-access file streams flow only in one direction. </li></ul><ul><li>See the diagram on the next slide  </li></ul>
  87. 87. Overview --- Streams <ul><li>A stream is an abstraction of a continuous one-way flow of data . </li></ul>
  88. 88. Overview and Background <ul><li>The original version of Java defined only the byte stream , but character streams were quickly added. </li></ul><ul><li>Byte streams can be used when reading or writing binary data. </li></ul><ul><li>Character streams are designed for handling character I/O. </li></ul><ul><li>Character streams use UNICODE . In Java, a character is 2 bytes </li></ul><ul><li>Unicode is for the internationalization of Java in different languages . </li></ul><ul><li>The Java I/O system is quite LARGE because of the TWO separate class hierarchies of bytes and streams. </li></ul>
  89. 89. How is I/O Handled in Java? <ul><li>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. </li></ul>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. 90. Text Files vs. Binary Files <ul><li>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. </li></ul><ul><li>The advantage of binary files is that they are more efficient to process than text files. </li></ul><ul><li>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 ) </li></ul>
  91. 91. Binary I/O <ul><li>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. </li></ul>
  92. 92. 2 Types of Stream Classes: Bytes & Characters <ul><li>The stream classes can be categorized into two types: byte streams and character streams . </li></ul><ul><li>The InputStream/OutputStream class is the root of all byte stream classes </li></ul><ul><li>The Reader/Writer class is the root of all character stream classes. </li></ul><ul><li>The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer . </li></ul>
  93. 93. Byte Stream Classes (note: “stream” )
  94. 94. Character Stream Classes (Character = 2 bytes)
  95. 95. Predefined Streams in Java <ul><li>All Java programs automatically import the java.lang package. </li></ul><ul><li>The java.lang package defines a class called System which encapsulates several aspects of the runtime environment. </li></ul><ul><li>The System class contains 3 predefined stream variables called: </li></ul><ul><li>in, out, and err (System.in, System.out, System.err) </li></ul><ul><li>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. </li></ul>
  96. 96. Predefined Streams in Java: System class <ul><li>System.in refers to the standard input stream which is the keyboard by default. (Keyboard ) </li></ul><ul><li>System.out refers to the standard output stream which is the console by default. (Monitor) </li></ul><ul><li>System.err refers to the standard error stream which is also the console by default. (Monitor) </li></ul><ul><li>These streams may be redirected to any compatible I/O device . </li></ul>
  97. 97. Predefined Streams in Java: System class <ul><li>System.in is an object of type InputStream. (byte stream) </li></ul><ul><li>System.out is an object of type PrintStream. (byte stream) </li></ul><ul><li>System.err is an object of type PrintStream. (byte stream) </li></ul><ul><li>They are all byte streams and are a part of the original Java specification. </li></ul><ul><li>They are NOT character streams ! (Unicode character = 2 bytes) </li></ul>
  98. 98. Reading Keyboard Input <ul><li>// Read an array of bytes from the keyboard. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class ReadBytes { </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>throws IOException { </li></ul><ul><li>byte data[ ] = new byte[10]; // Byte array “data” holds 10 bytes </li></ul><ul><li>System.out.println(&quot;Enter some characters:&quot;); </li></ul><ul><li>System.in.read(data); // Use the “read” method to read some bytes </li></ul><ul><li>System.out.print(&quot;You entered: &quot;); </li></ul><ul><li>for(int i=0; i < data.length; i++) </li></ul><ul><li>System.out.print((char) data[i]); // Cast data to a character </li></ul><ul><li>} // End main method </li></ul><ul><li>} // End class ReadBytes </li></ul>
  99. 99. Reading Keyboard Input <ul><li>Here is a sample run from the previous program: </li></ul><ul><li>Enter some characters: (prompt from program) </li></ul><ul><li>READ BYTES (User entered READ BYTES) </li></ul><ul><li>You entered: READ BYTES (output from program) </li></ul>
  100. 100. Writing Output to the Monitor <ul><li>// Demonstrate System.out.write(). Java program WriteDemo.java </li></ul><ul><li>public class WriteDemo </li></ul><ul><li>{ </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>{ </li></ul><ul><li>int b; // Program prints an ‘X’ on the monitor </li></ul><ul><li>b = 'X'; // The character is an int </li></ul><ul><li>System.out.write(b); // A byte stream; write low-order 8 bits </li></ul><ul><li>System.out.write(' '); // Print a newline character </li></ul><ul><li>} // End of main( ) // print() and println() are easier to use than write() </li></ul><ul><li>} // End of class WriteDemo </li></ul>
  101. 101. Stream classes (Bytes & Characters) <ul><li>The java.io package provides two categories of classes: </li></ul><ul><ul><li>Byte stream readers and writers </li></ul></ul><ul><ul><li>Character stream readers and writers </li></ul></ul><ul><li>At the top of the hierarchy for stream classes are the abstract classes InputStream and Output Stream </li></ul><ul><li>The subclasses branch out and specializes into the different types of streams that they handle. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>
  102. 102. Stream Classes <ul><li>FileInputStream can read raw streams of data from files. </li></ul><ul><li>DataOutputStream can write primitive data; this class implements the OutputData interface </li></ul><ul><li>RandomAccessFile implements both InputData and OutputData interfaces, therefore, it can read and write data to streams. </li></ul><ul><li>ObjectOutputStream implements the ObjectOutput interface and can write object data to streams. </li></ul>
  103. 103. InputStream Class (for reading bytes) <ul><li>The following methods are defined in InputStream </li></ul><ul><li>and are often useful: </li></ul><ul><li>public abstract int read() throws IOException </li></ul><ul><li>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. </li></ul><ul><li>public int read(byte b[]) throws IOException </li></ul><ul><li>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. </li></ul>
  104. 104. InputStream Class (for reading bytes) <ul><li>The following methods are defined in InputStream and are often useful: </li></ul><ul><li>public void close() throws IOException </li></ul><ul><li>This method closes the input stream. </li></ul><ul><li>public void available() throws IOException </li></ul><ul><li>Returns the number of bytes that can be read from the input stream without blocking. </li></ul>
  105. 105. InputStream Class (for reading bytes) <ul><li>The following method is defined in InputStream and is often useful: </li></ul><ul><li>public long skip(long n) throws IOException </li></ul><ul><li>Skip over and discard n bytes of data from the input stream. The actual number of bytes skipped is returned. </li></ul>
  106. 106. Reading & Writing Files Using Byte Streams <ul><li>To create a byte stream linked to a file, use FileInputStream or FileOutputStream </li></ul><ul><li>To open a file, create an object of one of these classes, specifying the name of the file as an argument to the constructor . </li></ul><ul><li>Once the file is open, you can read from the file or write to the file. </li></ul><ul><li>To read form a file, you may use the read( ) method. </li></ul><ul><li>int read( ) throws IOException </li></ul><ul><li>When you are done with a file, you should close it by calling close() </li></ul><ul><li>void close( ) throws IOException </li></ul><ul><li>Closing a file releases the system resources allocated to the file, allowing them to be used by another file. </li></ul>
  107. 107. Reading & Writing Files Using Byte Streams <ul><li>/* Display a text file. </li></ul><ul><li>To use this program, specify the name </li></ul><ul><li>of the file that you want to see. </li></ul><ul><li>For example, to see a file called TEST.TXT, </li></ul><ul><li>use the following command line. </li></ul><ul><li>Command line usage: java ShowFile TEST.TXT */ </li></ul><ul><li>// Program ShowFile.java follows on the next slide -> </li></ul>
  108. 108. Reading & Writing Files Using Byte Streams <ul><li>public class ShowFile { </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>throws IOException { </li></ul><ul><li>int i; </li></ul><ul><li>FileInputStream fin; // Declare file pointer </li></ul><ul><li>try { </li></ul><ul><li>fin = new FileInputStream(args[0]); } // Open the input file </li></ul><ul><li>catch(FileNotFoundException exc) { </li></ul><ul><li>System.out.println(“Error: “ + exc.getMessage( )); </li></ul><ul><li>System.out.println(&quot;File Not Found&quot;); </li></ul><ul><li>return; } </li></ul><ul><li>} catch(ArrayIndexOutOfBoundsException exc) { </li></ul><ul><li>System.out.println(“Error: “ + exc.getMessage( )); </li></ul><ul><li>System.out.println(&quot;Usage is: java ShowFile File.txt &quot;); </li></ul><ul><li>return; } </li></ul>
  109. 109. Reading & Writing Files Using Byte Streams <ul><li>// Read bytes until EOF is encountered </li></ul><ul><li>do { </li></ul><ul><li>i = fin.read( ); // Read an integer </li></ul><ul><li>if(i != -1) System.out.print((char) i); // Cast the int as a char </li></ul><ul><li>} while( i != -1); // When i = -1, EOF is encountered </li></ul><ul><li>fin.close( ); // Close the input file </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class ShowFile </li></ul>
  110. 110. Writing to a File Using Byte Streams <ul><li>/* Java program to Copy a text file. </li></ul><ul><li>To use this program, specify the name </li></ul><ul><li>of the source file and the destination file. </li></ul><ul><li>For example, to copy a file called File1.txt </li></ul><ul><li>to a file called File2.txt , use the following </li></ul><ul><li>on the command line: </li></ul><ul><li>Usage: java CopyFile File1.txt File2.txt */ </li></ul>
  111. 111. Writing to a File Using Byte Streams <ul><li>// CopyFile.java Demo byte stream file operations </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class CopyFile { </li></ul><ul><li>public static void main(String[ ] args) throws IOException </li></ul><ul><li>{ </li></ul><ul><li>int i; </li></ul><ul><li>FileInputStream fin; // Declare 2 byte stream files (pointers) </li></ul><ul><li>FileOutputStream fout; // Output file pointer </li></ul>
  112. 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. 113. Writing to a File Using Byte Streams <ul><li>// open output file </li></ul><ul><li>try { </li></ul><ul><li>fout = new FileOutputStream(args[1]); </li></ul><ul><li>} catch(FileNotFoundException exc) { </li></ul><ul><li>System.out.println(“Error: “ + exc.getMessage()); </li></ul><ul><li>System.out.println(&quot;Error Opening Output File&quot;); </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul><ul><li>} // End of outer try block </li></ul>
  114. 114. Writing to a File Using Byte Streams <ul><li>catch(ArrayIndexOutOfBoundsException exc) { </li></ul><ul><li>System.out.println(“Error: “ + exc.getMessage( ) ); </li></ul><ul><li>System.out.println(&quot;Usage: CopyFile File1 File2&quot;); </li></ul><ul><li>return; } </li></ul><ul><li>try { // Try to copy file1 to file2 </li></ul><ul><li>do { </li></ul><ul><li>i = fin.read( ); // Read a byte </li></ul><ul><li>if(i != -1) fout.write(i); // Write the byte to the output file </li></ul><ul><li>} while(i != -1); // Loop while not at EOF (-1) </li></ul><ul><li>} // End of try block </li></ul><ul><li>catch(IOException exc) </li></ul><ul><li>{ System.out.println(&quot;File Error&quot;); } </li></ul><ul><li>fin.close( ); // Close the input file </li></ul><ul><li>fout.close( ); // Close the output file </li></ul><ul><li>} // End of main( ) method </li></ul><ul><li>} // End of class CopyFile </li></ul>
  115. 115. Reading & Writing Binary Data <ul><li>So far, we have been reading and writing bytes containing ASCII bytes. </li></ul><ul><li>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. </li></ul><ul><li>In Java, to read and write binary values of the simple Java data types, you should use: </li></ul><ul><li>DataInputStream and DataOutputStream (for binary data) </li></ul><ul><li>DataOutputStream implements the OutputData interface . </li></ul><ul><li>The OutputData interface defines methods that write all of Java’s simple data types to a file. </li></ul>
  116. 116. Reading & Writing Binary Data <ul><li>Note: Binary data is NOT in human-readable text format, obviously. </li></ul><ul><li>The constructor for DataOutputStream is: </li></ul><ul><li>DataOutputStream(OutputStream outputStream ) </li></ul><ul><li>outputStream is the stream to which the binary data is written. </li></ul>
  117. 117. Reading & Writing Binary Data <ul><li>The constructor for DataInputStream is: </li></ul><ul><li>DataInputStream(InputStream inputStream ) </li></ul><ul><li>inputStream is the stream that is linked to the instance of </li></ul><ul><li>DataInputStream being created. </li></ul><ul><li>DataInputStream implements the DataInput interface which provides the methods for reading all of Java’s simple data types. </li></ul><ul><li>DataInputStream uses an InputStream instance as its foundation, overlaying it with methods that read the various Java data types. </li></ul>
  118. 118. Reading & Writing Binary Data Examples <ul><li>To create an input stream for the file in.dat ( bytes) </li></ul><ul><li>DataInputStream infile = </li></ul><ul><li>new DataInputStream(new FileInputStream(“in.dat”)); </li></ul><ul><li>To create an output stream for the file out.dat: </li></ul><ul><li>DataOutputStream outfile = </li></ul><ul><li>new DataOutputStream(new FileOutputStream(“out.dat”)); </li></ul>
  119. 119. Reading & Writing Binary Data <ul><li>Common Input Methods Defined by DataInputStream (a byte stream) </li></ul><ul><li>Input Method Purpose </li></ul><ul><li>boolean readBoolean ( ) Reads a boolean </li></ul><ul><li>byte readByte ( ) Reads a byte </li></ul><ul><li>char readChar ( ) Reads a char </li></ul><ul><li>double readDouble( ) Reads a double </li></ul><ul><li>float readFloat ( ) Reads a float </li></ul><ul><li>int readInt ( ) Reads an int </li></ul><ul><li>long readLong ( ) Reads a long </li></ul><ul><li>short readShort ( ) Reads a short </li></ul>
  120. 120. Reading & Writing Binary Data <ul><li>Common Output Methods Defined by DataOutputStream ( byte stream) </li></ul><ul><li>Output Method Purpose </li></ul><ul><li>void writeBoolean (boolean val) writes the boolean specified by val </li></ul><ul><li>void writeByte (int val) writes the low-order byte val </li></ul><ul><li>void writeChar(int val) writes the value val as a char </li></ul><ul><li>void writeDouble(double val) writes the double val </li></ul><ul><li>void writeFloat(float val) writes the float val </li></ul><ul><li>void writeInt(int val) writes the int val </li></ul><ul><li>void writeLong(long val) writes the long val </li></ul><ul><li>void writeShort(int val) writes val as a short </li></ul>
  121. 121. Reading & Writing Binary Data <ul><li>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. </li></ul><ul><li>// Write and then read back binary data. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class RWData { </li></ul><ul><li>public static void main(String[ ] args) throws IOException </li></ul><ul><li>{ </li></ul><ul><li>DataOutputStream dataOut; // Declare output, input file pointers </li></ul><ul><li>DataInputStream dataIn; </li></ul>
  122. 122. Reading & Writing Binary Data <ul><li>int i = 120; </li></ul><ul><li>double d = 1049.56; </li></ul><ul><li>boolean b = true; </li></ul><ul><li>try { </li></ul><ul><li>dataOut = new </li></ul><ul><li>DataOutputStream(new FileOutputStream(“testdata&quot;)); } </li></ul><ul><li>catch(IOException exc) { </li></ul><ul><li>System.out.println(“Error: “ + exc.getMessage( )); </li></ul><ul><li>System.out.println(&quot;Cannot open file.&quot;); </li></ul><ul><li>return; } </li></ul>
  123. 123. Reading & Writing Binary Data <ul><li>try { // Write the binary data </li></ul><ul><li>System.out.println(&quot;Writing &quot; + i); </li></ul><ul><li>dataOut.writeInt(i); </li></ul><ul><li>System.out.println(&quot;Writing &quot; + d); </li></ul><ul><li>dataOut.writeDouble(d); </li></ul><ul><li>System.out.println(&quot;Writing &quot; + b); </li></ul><ul><li>dataOut.writeBoolean(b); </li></ul><ul><li>System.out.println(&quot;Writing &quot; + 12.2 * 7.4); </li></ul><ul><li>dataOut.writeDouble(12.2 * 7.4); </li></ul><ul><li>} </li></ul>
  124. 124. Reading & Writing Binary Data <ul><li>catch(IOException exc) { </li></ul><ul><li>System.out.println(&quot;Write error: + exc.getMessage( )&quot;); </li></ul><ul><li>} </li></ul><ul><li>dataOut.close( ); </li></ul><ul><li>System.out.println(); // Print a blank line </li></ul><ul><li>// Now, read them back. </li></ul><ul><li>try { </li></ul><ul><li>dataIn = new </li></ul><ul><li>DataInputStream(new FileInputStream(&quot;testdata&quot;)); </li></ul><ul><li>} </li></ul><ul><li>catch(IOException exc) { </li></ul><ul><li>System.out.println(&quot;Cannot open file. + exc.getMessage( )&quot;); </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul>
  125. 125. Reading & Writing Binary Data <ul><li>try { // Read the binary data </li></ul><ul><li>i = dataIn.readInt(); </li></ul><ul><li>System.out.println(&quot;Reading &quot; + i); </li></ul><ul><li>d = dataIn.readDouble(); </li></ul><ul><li>System.out.println(&quot;Reading &quot; + d); </li></ul><ul><li>b = dataIn.readBoolean(); </li></ul><ul><li>System.out.println(&quot;Reading &quot; + b); </li></ul><ul><li>d = dataIn.readDouble(); </li></ul><ul><li>System.out.println(&quot;Reading &quot; + d); </li></ul><ul><li>} </li></ul>
  126. 126. Reading & Writing Binary Data <ul><li>catch(IOException exc) { </li></ul><ul><li>System.out.println(&quot;Read error.“ + exc.getMessage( ) ); } </li></ul><ul><li>dataIn.close(); </li></ul><ul><li>} // End of main ( ) </li></ul><ul><li>} // End of class RWData </li></ul><ul><li>The output from the previous program follows: </li></ul><ul><li>Writing 120 Reading 120 </li></ul><ul><li>Writing 1023.56 Reading 1049.56 </li></ul><ul><li>Writing true Reading true </li></ul><ul><li>Writing 90.28 Reading 90.28 </li></ul>
  127. 127. Reader class methods for reading characters <ul><li>The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation. </li></ul><ul><li>Remember: A character is 2 bytes ! </li></ul><ul><li>public abstract int read() throws IOException </li></ul><ul><li>public int read(char b[]) throws IOException </li></ul><ul><li>public void close() throws IOException </li></ul><ul><li>public void skip() throws IOException </li></ul>
  128. 128. OutputStream ( bytes) & Writer (for characters) <ul><li>Like InputStream (for reading bytes ) and Reader (for reading characters ), OutputStream and Writer are the counterparts. </li></ul><ul><li>They are the base classes for for all output streams of bytes and characters, respectively. </li></ul><ul><li>The next slide shows methods which are in both OutputStream and Writer . </li></ul><ul><li> See next slide -> </li></ul>
  129. 129. OutputStream (Writing bytes) <ul><li>public abstract void write(int b) throws IOException </li></ul><ul><li>Write a byte b (for OutputStream) or a charcter (for Writer) </li></ul><ul><li>public void write(byte[] b) throws IOException </li></ul><ul><li>This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer) </li></ul><ul><li>public void close() throws IOException </li></ul><ul><li>This method closes the output stream. </li></ul><ul><li>public void flush() throws IOException </li></ul><ul><li>Flush the output stream and send any buffered data in the stream to its destination. </li></ul>
  130. 130. Writer (Writing characters) (Same as OutputStream) <ul><li>public abstract void write(int b) throws IOException </li></ul><ul><li>Write a byte b (for OutputStream) or a character (for Writer) </li></ul><ul><li>public void write(byte[] b) throws IOException </li></ul><ul><li>This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer) </li></ul><ul><li>public void close() throws IOException </li></ul><ul><li>This method closes the output stream. </li></ul><ul><li>public void flush() throws IOException </li></ul><ul><li>Flush the output stream and send any buffered data in the stream to its destination. </li></ul>
  131. 131. Console Input using Character Streams <ul><li>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. </li></ul><ul><li>Since System.in is a byte-stream, you need to wrap System.in inside of some type of Reader . </li></ul><ul><li>The best class for reading console input is BufferedReader which supports a buffered input stream. (BufferedReader inherits from Reader) </li></ul><ul><li>But, you cannot construct a BufferedReader directly from System.in </li></ul>
  132. 132. Console Input using Character Streams <ul><li>You must first convert the input from System.in from a byte stream into a character stream. To do this, you must use InputStreamReader. </li></ul><ul><li>InputStreamReader converts bytes to characters. </li></ul><ul><li>To obtain an InputStreamReader object that is linked to System.in , use the following constructor: </li></ul><ul><li>InputStreamReader ( InputStream inputStream ) </li></ul><ul><li>Since System.in refers to an object of type InputStream, it can be used for inputStream such as in: InputStreamReader(System.in) </li></ul>
  133. 133. Console Input using Character Streams <ul><li>Next, using the object produced by InputStreamReader, construct a BufferedReader using the following constructor: </li></ul><ul><li>BufferedReader(Reader inputReader ) </li></ul><ul><li>Here , inputReader is the stream that is linked to the instance of BufferedReader being created. </li></ul>
  134. 134. Console Input using Character Streams <ul><li>Putting it all together, the following line of code creates a BufferReader that is connected to the keyboard. </li></ul><ul><li>BufferedReader br = </li></ul><ul><li>new BufferedReader( new InputStreamReader(System.in)); </li></ul><ul><li>After the above statement executes, “br” will be a character -based </li></ul><ul><li>stream that is linked to the console thru System.in (which reads bytes) </li></ul>
  135. 135. Console Input using Character Streams <ul><li>Reading Characters </li></ul><ul><li>Characters can be read from System.in using the read( ) method defined by BufferedReader. </li></ul><ul><li>BufferedReader defines the following versions of read( ) </li></ul><ul><li>int read( ) throws IOException </li></ul><ul><li>int read(char data[ ] ) throws IOException </li></ul><ul><li>int read(char data[ ], int start, int max) throws IOException </li></ul>
  136. 136. Console Input using Character Streams <ul><li>int read( ) throws IOException </li></ul><ul><li>reads a single Unicode character and returns a -1 when the end of the stream is reached. </li></ul><ul><li>int read(char data [ ]) throws IOException </li></ul><ul><li>reads characters from the input stream until: </li></ul><ul><li>(1) the array is full, (2) EOF is reached, or (3) an error occurs. </li></ul><ul><li>int read(char data [ ], int start , int max ) throws IOException </li></ul><ul><li>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. </li></ul><ul><li>Pressing the [Enter] key generates an end-of-stream condition. </li></ul>
  137. 137. Console Input using Character Streams <ul><li>The following program demonstrates the read( ) method by reading characters from the console until the user types a period. </li></ul><ul><li>// Use a BufferedReader to read characters from the console. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class ReadChars { </li></ul><ul><li>public static void main(String[ ] args) throws IOException </li></ul><ul><li>{ </li></ul>
  138. 138. Console Input using Character Streams <ul><li>BufferedReader br = new </li></ul><ul><li>BufferedReader(new InputStreamReader(System.in)); </li></ul><ul><li>System.out.println(&quot;Enter some characters; period to quit.&quot;); </li></ul><ul><li>// read characters </li></ul><ul><li>do { </li></ul><ul><li>c = (char) br.read(); // Cast the character to a byte </li></ul><ul><li>System.out.println(c); // Print the character </li></ul><ul><li>} while(c != '.'); // Loop as long as the input char is not a period </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of ReadChars class </li></ul>
  139. 139. Console Input using Character Streams <ul><li>Output from the previous program could be: </li></ul><ul><li>Enter some characters; period to quit. </li></ul><ul><li>I </li></ul><ul><li>T </li></ul><ul><li>P </li></ul><ul><li>J </li></ul><ul><li>A </li></ul><ul><li>V </li></ul><ul><li>A </li></ul><ul><li>. <- note the period character which stopped the input stream </li></ul>
  140. 140. Console Input using Character Streams <ul><li>Reading Character Strings from the Keyboard … </li></ul><ul><li>To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. The general form is: </li></ul><ul><li>String readLine( ) throws IOException </li></ul><ul><li>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. </li></ul>
  141. 141. Console Input using Character Streams <ul><li>The following program demonstrates BufferedReader and the readLine() method. The program reads and displays lines of text until the user enters the word “stop” </li></ul><ul><li>// Read a string from console using a BufferedReader. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>class ReadLines { </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>throws IOException </li></ul><ul><li>{ </li></ul><ul><li>// create a BufferedReader using System.in </li></ul><ul><li>BufferedReader br = new BufferedReader(new </li></ul><ul><li>InputStreamReader(System.in)); </li></ul><ul><li>String str; </li></ul>
  142. 142. Console Input using Character Streams <ul><li>System.out.println(&quot;Enter lines of text.&quot;); </li></ul><ul><li>System.out.println(&quot;Enter 'stop' to quit.&quot;); </li></ul><ul><li>do { </li></ul><ul><li>str = br.readLine(); </li></ul><ul><li>System.out.println(str); </li></ul><ul><li>} while(!str.equals(&quot;stop&quot;)); </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class ReadLines </li></ul>
  143. 143. Console Output using Character Streams <ul><li>The preferred method of writing to the console (monitor) when using Java is through a PrintWriter stream. </li></ul><ul><li>PrintWriter is one of the character-based classes. </li></ul><ul><li>Using a character-based class makes it easier to internationalize </li></ul><ul><li>Java programs. </li></ul><ul><li>PrintWriter has several constructors, but this is the one to be used in the demonstration program which is on the following slides: </li></ul><ul><li>PrintWriter(OutputStream outputStream , boolean flushOnNewline) </li></ul>
  144. 144. Console Output using Character Streams <ul><li>PrintWriter(OutputStream outputStream , boolean flushOnNewline) </li></ul><ul><li>Here, outputStream is an object of type OutputStream. </li></ul><ul><li>flushOnNewLine controls whether Java flushes the output stream every time a println( ) method is called. </li></ul><ul><li>If flushOnNewLine is true flushing automatically takes place. </li></ul><ul><li>If flushOnNewLine is false , flushing is not automatic. </li></ul>
  145. 145. Console Output using Character Streams <ul><li>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( ). </li></ul><ul><li>For example, the following line of code creates a PrintWriter that is connected to console (monitor) output. </li></ul><ul><li>PrintWriter pw = new PrintWriter(System.out, true); </li></ul><ul><li>The Java program on the next slide demonstrates a PrintWriter  </li></ul>
  146. 146. Console Output using Character Streams <ul><li>// Demonstrate PrintWriter. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class PrintWriterDemo { </li></ul><ul><li>public static void main(String[ ] args) { </li></ul><ul><li>PrintWriter pw = new PrintWriter(System.out, true); </li></ul><ul><li>int i = 120; </li></ul><ul><li>double d = 123.67; </li></ul>
  147. 147. Console Output using Character Streams <ul><li>pw.println(&quot;Using a PrintWriter.&quot;); // PrintWriter Demo </li></ul><ul><li>pw.println(i); </li></ul><ul><li>pw.println(d); </li></ul><ul><li>pw.println(i + &quot; + &quot; + d + &quot; is &quot; + i +d); </li></ul><ul><li>} // End of main( ) method </li></ul><ul><li>} // End of class PrintWriterDemo </li></ul><ul><li>The output from the previous program is: </li></ul><ul><li>Using a PrintWriter. </li></ul><ul><li>120 </li></ul><ul><li>123.67 </li></ul><ul><li>120 + 123.67 is 243.67 </li></ul>
  148. 148. File Input & Output using Character Streams <ul><li>In general, to perform character-based file I/O, you will use the FileReader and FileWriter classes. </li></ul><ul><li>Using a FileWriter </li></ul><ul><li>FileWriter creates a Writer that you can use to write to a file. </li></ul><ul><li>FileWriter is derived from OutputStreamWriter and Writer classes </li></ul><ul><li>Commonly used constructors are: </li></ul><ul><li>FileWriter (String fileName) throws IOException </li></ul><ul><li>FileWriter (String fileName, boolean append ) throws IOException </li></ul><ul><li>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. </li></ul>
  149. 149. File I / O using Character Streams FileWriter <ul><li>// A simple keyboard-to-disk utility that demonstrates a FileWriter. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class KtoD { </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>throws IOException { </li></ul><ul><li>String str; </li></ul><ul><li>FileWriter fw; </li></ul><ul><li>BufferedReader br = </li></ul><ul><li>new BufferedReader( new InputStreamReader(System.in)); </li></ul>
  150. 150. File I / O using Character Streams FileWriter <ul><li>try { </li></ul><ul><li>fw = new FileWriter(&quot;test.txt&quot;); // Try to open the file </li></ul><ul><li>} </li></ul><ul><li>catch(IOException exc) { </li></ul><ul><li>System.out.println(“Error: “ + exc.getMessage( ) ); </li></ul><ul><li>System.out.println(&quot;Cannot open output file.&quot;); </li></ul><ul><li>return ; </li></ul><ul><li>} </li></ul>
  151. 151. File I / O using Character Streams FileWriter <ul><li>System.out.println(&quot;Enter text ('stop' to quit).&quot;); </li></ul><ul><li>do { </li></ul><ul><li>System.out.print(&quot;: &quot;); </li></ul><ul><li>str = br.readLine( ); </li></ul><ul><li>if(str.compareTo(&quot;stop&quot;) == 0) break; </li></ul><ul><li>str = str + &quot; &quot;; // add carriage return & newline </li></ul><ul><li>fw.write(str); </li></ul><ul><li>} while(str.compareTo(&quot;stop&quot;) != 0); </li></ul><ul><li>fw.close( ); </li></ul><ul><li>} // End of main ( ) method </li></ul><ul><li>} // End of class KtoD </li></ul>
  152. 152. File I / O using Character Streams FileReader <ul><li>The FileReader class creates a Reader that you can use to read the </li></ul><ul><li>contents of a file. FileReader is derived from the InputStreamReader and Reader classes. It has access to the methods in those classes. </li></ul><ul><li>The most common constructor is: </li></ul><ul><li>FileReader(String fileName ) throws FileNotFoundException </li></ul><ul><li>where fileName is the full path name of the file. </li></ul><ul><li>It throws a FileNotFoundException if the file does not exist. </li></ul>
  153. 153. File I / O using Character Streams FileReader <ul><li>The following program reads a text file called “test.txt” and displays the information on the screen. </li></ul><ul><li>// A simple disk-to-screen utilitiy that demonstrates a FileReader. </li></ul><ul><li>import java.io.*; </li></ul><ul><li>class DtoS { </li></ul><ul><li>public static void main(String[ ] args) throws Exception </li></ul><ul><li>{ </li></ul><ul><li>FileReader fr = new FileReader(&quot;test.txt&quot;); </li></ul><ul><li>BufferedReader br = new BufferedReader(fr); </li></ul><ul><li>String s; </li></ul>
  154. 154. File I / O using Character Streams FileReader <ul><li>while((s = br.readLine()) != null) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(s); </li></ul><ul><li>} </li></ul><ul><li>fr.close( ); // Close the file </li></ul><ul><li>} // End of main( ) method </li></ul><ul><li>} // End of DtoS class </li></ul>
  155. 155. The File Class: Objectives <ul><ul><li>To discover file properties, delete and rename files using the File class </li></ul></ul><ul><ul><li>To understand how I/O is processed in Java </li></ul></ul><ul><ul><li>To distinguish between text I/O and binary I/O </li></ul></ul><ul><ul><li>To read and write characters using FileReader and FileWriter </li></ul></ul><ul><ul><li>To improve the performance of text I/O using BufferedReader and BufferedWriter </li></ul></ul><ul><ul><li>To write primitive values, strings, and objects as text using PrintWriter and PrintStream </li></ul></ul><ul><ul><li>To read and write bytes using FileInputStream and FileOutputStream </li></ul></ul><ul><ul><li>To read and write primitive values and strings using DataInputStream / DataOutputStream </li></ul></ul><ul><ul><li>To store and restore objects using ObjectOutputStream and ObjectInputStream , and to understand how objects are serialized and what kind of objects can be serialized </li></ul></ul><ul><ul><li>To use RandomAccessFile for both read and write. </li></ul></ul>
  156. 156. The File Class <ul><li>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. </li></ul><ul><li>The File class is a wrapper class for the file name and its directory path. </li></ul>
  157. 157. Obtaining file properties and manipulating file
  158. 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. 159. The File Class and Processing External Files <ul><li>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. </li></ul><ul><li>You can create a new File object using the following statement: </li></ul><ul><li>File myfile = new File (“myfile.dat”); </li></ul><ul><li>You can use the File class to check properties of files, such as whether the file exists , or is readable , or updateable . </li></ul>
  160. 160. The File Class and Processing External Files <ul><li>You can use the getName( ) method to get the name of the file. </li></ul><ul><li>For example, </li></ul><ul><li>if (myfile.exists( ) ) </li></ul><ul><li>System.out.println(“File “ + myfile.getName( ) + “ already exists”); </li></ul><ul><li>The following statement creates a file using the full path using the Windows operating system: </li></ul><ul><li>File myfile = new File(“C:avayfile.data”); </li></ul>
  161. 161. The File Class and Processing External Files <ul><li>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. </li></ul><ul><li>For example, </li></ul><ul><li>if (myfile.exists( ) ) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“The full path is “ + myfile.getPath( ) ); </li></ul><ul><li>System.out.println(“The directory is “ + myfile.getParent( ) ); </li></ul><ul><li>} </li></ul>
  162. 162. Demo Program: TestFileClass.java <ul><li>// TestFileClass.java: Demonstrate the File class Chapt 18 I/O ITP120 </li></ul><ul><li>import java.io.*; </li></ul><ul><li>import java.util.*; </li></ul><ul><li>public class TestFileClass { </li></ul><ul><li>public static void main(String[] args) { </li></ul><ul><li>// Create a File object </li></ul><ul><li>File file = new File(&quot;.&quot;, &quot;images&quot; + File.separator + &quot;bill_gates.gif&quot;); </li></ul><ul><li>System.out.println(&quot;Does it exist? &quot; + file.exists()); </li></ul><ul><li>System.out.println(&quot;Can it be read? &quot; + file.canRead()); </li></ul><ul><li>System.out.println(&quot;Can it be written? &quot; + file.canRead()); </li></ul><ul><li>System.out.println(&quot;Is it a directory? &quot; + file.isDirectory()); </li></ul><ul><li>System.out.println(&quot;Is it a file? &quot; + file.isFile()); </li></ul><ul><li>System.out.println(&quot;Is it absolute? &quot; + file.isAbsolute()); </li></ul><ul><li>System.out.println(&quot;Is it hidden? &quot; + file.isHidden()); </li></ul><ul><li>System.out.println(&quot;What is its absolute path? &quot; + </li></ul><ul><li>file.getAbsolutePath()); </li></ul>
  163. 163. Demo Program: TestFileClass.java <ul><li>try { </li></ul><ul><li>System.out.println(&quot;What is its canonical path? &quot; + </li></ul><ul><li>file.getCanonicalPath()); </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) { } </li></ul><ul><li>System.out.println(&quot;What is its name? &quot; + file.getName()); </li></ul><ul><li>System.out.println(&quot;What is its path? &quot; + file.getPath()); </li></ul><ul><li>System.out.println(&quot;When was it last modified? &quot; + </li></ul><ul><li>new Date(file.lastModified())); </li></ul><ul><li>System.out.println(&quot;What is the path separator? &quot; + </li></ul><ul><li>File.pathSeparatorChar); </li></ul><ul><li>System.out.println(&quot;What is the name separator? &quot; + </li></ul><ul><li>File.separatorChar); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  164. 164. Processing External Files <ul><li>Again, you must use file streams to read from or write to a disk file. </li></ul><ul><li>Once again, you can use FileInputStream or FileOutputStream for byte streams. </li></ul><ul><li>And you can use FileReader or FileWriter for character streams. </li></ul>
  165. 165. File I/O Stream Constructors <ul><li>To create a file stream, use these constructors: </li></ul><ul><li>public FileInputStream (String filenameString) // Byte stream constructors </li></ul><ul><li>public FileInputStream (File file) </li></ul><ul><li>public FileOutputStream (String filenameString) // Byte stream constructor </li></ul><ul><li>public FileOutputStream (File file) </li></ul><ul><li>public FileReader (String filenameString) // Character stream constructors </li></ul><ul><li>public FileReader (File file) </li></ul><ul><li>public FileWriter (String filenameString) // Character stream constructor </li></ul><ul><li>public FileWriter (File file) </li></ul>
  166. 166. File I/O Stream Constructors <ul><li>Constructing instances of FileInputStream , FileOutputStream , FileReader , and FileWriter from file names: </li></ul>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. 167. Demo Program: TestFileReader.java <ul><li>// TestFileReader.java Chapter 18 I/O ITP 120 </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class TestFileReader { </li></ul><ul><li>public static void main(String[ ] args) { </li></ul><ul><li>FileReader input = null; </li></ul><ul><li>try { </li></ul><ul><li>// Create an input stream </li></ul><ul><li>input = new FileReader(&quot;temp.txt&quot;); </li></ul><ul><li>int code; </li></ul><ul><li>// Repeatedly read a character and display it on the console </li></ul><ul><li>while ((code = input.read()) != -1) </li></ul><ul><li>System.out.print((char)code); </li></ul><ul><li>} // End of try block </li></ul>
  168. 168. Demo Program: TestFileReader.java <ul><li>System.out.println(&quot;File temp.txt does not exist&quot;); </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) { </li></ul><ul><li>ex.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>finally { </li></ul><ul><li>try { </li></ul><ul><li>input.close(); // Close the stream </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) { </li></ul><ul><li>ex.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} // End of class TestFileReader </li></ul>
  169. 169. Demo Program: TestFileWriter.java <ul><li>// TestFileWriter.java Chapter 18 File I/O ITP 120 </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class TestFileWriter { </li></ul><ul><li>public static void main(String[ ] args) throws IOException { </li></ul><ul><li>// Create an output stream to the file </li></ul><ul><li>FileWriter output = new FileWriter(&quot;temp.txt&quot;, true); </li></ul><ul><li>// Output a string to the file </li></ul><ul><li>output.write(“ NVCC Introduction to Java Programming ITP 120 !!!&quot;); </li></ul><ul><li>// Close the stream </li></ul><ul><li>output.close(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  170. 170. Processing External Files
  171. 171. Processing External Files <ul><li>The previous diagram shows that: </li></ul><ul><li>FileInputStream, fis, is used to read data (bytes) from a file </li></ul><ul><li>FileOutputStream, fos, is used to write data (bytes) to a file </li></ul><ul><li>Command line: </li></ul><ul><li>java CopyFileUsingByteStream f1.txt f2.txt </li></ul><ul><li>See the Java program CopyFileUsingByteStream on the following slides  </li></ul>
  172. 172. Processing External Files <ul><li>// CopyFileUsingByteStream.java For Copying files (byte streams) </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class CopyFileUsingByteStream </li></ul><ul><li>{ </li></ul><ul><li>// Main method: args[0] for sourcefile and args[1] for target file </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>{ </li></ul><ul><li>// Declare input and output file streams </li></ul><ul><li>FileInputStream fis = null; </li></ul><ul><li>FileOutputStream fos = null; </li></ul>
  173. 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. 174. Processing External Files <ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Create file input stream </li></ul><ul><li>fis = new FileInputStream(new File(args[0])); </li></ul><ul><li>// Create file output stream if the file does not exist </li></ul><ul><li>File outFile = new File(args[1]); </li></ul><ul><li>if (outFile.exists()) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;file &quot; + args[1] + &quot; already exists&quot;); </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul>
  175. 175. Processing External Files <ul><li>else </li></ul><ul><li>fos = new FileOutputStream(args[1]); // FileOutputStream </li></ul><ul><li>// Display the file size </li></ul><ul><li>System.out.println(&quot;The file &quot; + args[0] + &quot; has &quot;+ </li></ul><ul><li>fis.available() + &quot; bytes&quot;); </li></ul>
  176. 176. Processing External Files <ul><li>// Continuously read a byte from fis and write it to fos </li></ul><ul><li>int r; </li></ul><ul><li>while ((r = fis.read()) != -1) // EOF is -1 </li></ul><ul><li>fos.write((byte)r); </li></ul><ul><li>} </li></ul><ul><li>catch (FileNotFoundException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Error: “ + ex.getMessage( ) ); </li></ul><ul><li>System.out.println(&quot;File not found: &quot; + args[0]); </li></ul><ul><li>} </li></ul>
  177. 177. Processing External Files <ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Some IO Exception occurred”); </li></ul><ul><li>System.out.println(“Error: “ + ex.getMessage( )); </li></ul><ul><li>} </li></ul><ul><li>Continues to next slide  </li></ul>
  178. 178. Processing External Files <ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>if (fis != null) fis.close(); // Close the input & output files </li></ul><ul><li>if (fos != null) fos.close(); </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Error: “ + ex.getMessage( ) ); </li></ul><ul><li>} </li></ul><ul><li>} // End of finally block </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class CopyFileUsingByteStream </li></ul>
  179. 179. Filter Streams <ul><li>Filter streams are streams that filter bytes or characters for some purpose. </li></ul><ul><li>If you want to read integers , doubles , or Strings , you need a filter class to wrap the input stream. </li></ul><ul><li>Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters . </li></ul><ul><li>Use FilterInputStream and FilterOutputStream when you need to process primitive numeric types. </li></ul>
  180. 180. Filter Streams <ul><li>To process strings , use BufferedReader and PushbackReader to filter characters. </li></ul><ul><li>Note: FilterInputStream and FilterOutputStream are abstract classes. </li></ul>
  181. 181. FilterInputStream subclasses <ul><li>DataInputStream handles binary formats for all primitive data types. </li></ul><ul><li>BufferedInputStream gets data from the buffer and then reads them from the stream if necessary. </li></ul><ul><li>LineNumberInputStream keeps track of how many lines are read. </li></ul><ul><li>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. </li></ul>
  182. 182. FilterOutputStream subclasses <ul><li>DataOutputStream outputs the binary formats for all primitive data types which is useful if another program uses the output . </li></ul><ul><li>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. </li></ul><ul><li>PrintStream outputs the Unicode format of all primitive types which is useful if the format is output to the console . </li></ul>
  183. 183. Data Streams (bytes) <ul><li>The data streams ( DataInputStream and DataOutputStream ) </li></ul><ul><li>read and write Java primitive types in a machine-independent </li></ul><ul><li>fashion. </li></ul><ul><li>This enables you to write a data file for one computer </li></ul><ul><li>and read it on another computer that has a different operating system or file structure. </li></ul>
  184. 184. DataInputStream Methods defined in the DataInput Interface <ul><li>int readByte() throws IOException </li></ul><ul><li>int readShort() throws IOException </li></ul><ul><li>int readInt() throws IOException </li></ul><ul><li>int readLong() throws IOException </li></ul><ul><li>float readFloat() throws IOException </li></ul><ul><li>double readDouble() throws IOException </li></ul><ul><li>char readChar() throws IOException </li></ul><ul><li>boolean readBoolean() throws IOException </li></ul><ul><li>String readUTF() throws IOException </li></ul>
  185. 185. DataOutputStream Methods defined in the DataOutput interface <ul><li>void writeByte(byte b) throws IOException </li></ul><ul><li>void writeShort(short is) throws IOException </li></ul><ul><li>void writeInt(int i) throws IOException </li></ul><ul><li>void writeLong(long l) throws IOException </li></ul><ul><li>void writeFloat(float f) throws IOException </li></ul><ul><li>void writeDouble(double d) throws IOException </li></ul><ul><li>void writeChar(char c) throws IOException </li></ul><ul><li>void writeBoolean(boolean b) throws IOException </li></ul><ul><li>void writeBytes(String s) throws IOException </li></ul><ul><li>void writeChars(String s) throws IOException </li></ul><ul><li>void writeUTF(String s) throws IOException </li></ul>
  186. 186. DataInputStream & DataOutput Stream Constructors <ul><li>Data streams are used as wrappers on existing input and output streams to filter data in the original stream. </li></ul><ul><li>DataInputStream infile = new DataInputStream(new FileInputStream(&quot;in.dat&quot;)); </li></ul><ul><li>The above creates an input file for in.dat. </li></ul><ul><li>DataOutputStream outfile = new DataOutputStream(new FileOutputStream(&quot;out.dat&quot;)); </li></ul><ul><li>The above creates an output file for out.dat. </li></ul>
  187. 187. Using Data Streams <ul><li>The next example shows a program that: </li></ul><ul><li>Creates 10 random integers, </li></ul><ul><li>Stores them in a data file, </li></ul><ul><li>Retrieves data from the file, </li></ul><ul><li>Displays the integers on the console. </li></ul><ul><li> See next slide  </li></ul>
  188. 188. Using Data Streams Demo Example <ul><li>// TestDataStreams.java: Create a file, store it in binary form, and </li></ul><ul><li>// display the contents of the file on the console </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class TestDataStreams </li></ul><ul><li>{ </li></ul><ul><li>// Main method </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>{ </li></ul><ul><li>// Declare data input and output streams </li></ul><ul><li>DataInputStream dis = null; </li></ul><ul><li>DataOutputStream dos = null; </li></ul>
  189. 189. Using Data Streams Demo Example <ul><li>// Construct a temp file </li></ul><ul><li>File tempFile = new File(&quot;mytemp.dat&quot;); </li></ul><ul><li>// Check if the temp file exists </li></ul><ul><li>if (tempFile.exists()) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;The file mytemp.dat already exists,&quot; </li></ul><ul><li>+&quot; delete it, rerun the program&quot;); </li></ul><ul><li>System.exit(0); </li></ul><ul><li>} </li></ul>
  190. 190. Using Data Streams Demo Example <ul><li>// Write data </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Create data output stream for tempFile </li></ul><ul><li>dos = new DataOutputStream(new </li></ul><ul><li>FileOutputStream(tempFile)); </li></ul><ul><li>for (int i=0; i<10; i++) </li></ul><ul><li>dos.writeInt((int)(Math.random()*1000)); </li></ul><ul><li>} </li></ul>
  191. 191. Using Data Streams Demo Example <ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(ex.getMessage( ) ); </li></ul><ul><li>} </li></ul><ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>if (dos != null) dos.close( ); // Close the file(s) </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) </li></ul><ul><li>{ System.out.println(“Error: “ + ex.getMessage( ) ); } </li></ul>
  192. 192. Using Data Streams Demo Example <ul><li>// Read data </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Create data input stream </li></ul><ul><li>dis = new DataInputStream(new FileInputStream(tempFile)); </li></ul><ul><li>for (int i=0; i<10; i++) </li></ul><ul><li>System.out.print(&quot; &quot;+dis.readInt ( ) ); // Display the integers </li></ul><ul><li>} </li></ul>
  193. 193. Using Data Streams <ul><li>catch (FileNotFoundException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;File not found“ + ex.getMessage( ) );); </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(ex.getMessage()); </li></ul><ul><li>} </li></ul>
  194. 194. Using Data Streams <ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>if (dis != null) dis.close( ); // Close the file(s) </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Error: “ + ex.getMessage( ) )); </li></ul><ul><li>} </li></ul><ul><li>} // End of finally block </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class TestDataStreams </li></ul>
  195. 195. Using Data Streams Demo Example <ul><li>The previous Java program TestDataStreams.java creates a DataInputStream object named “dis” wrapped on FileInputStream and creates a DataOutputStream object “dos” wrapped on FileOutputStream </li></ul><ul><li>Conceptually, </li></ul><ul><li>Program  DataInputStream dis <-- fileInputStream <--mytemp.dat </li></ul><ul><li> DataOutputStream dos  fileOutputStream  mytemp.dat </li></ul><ul><li>The program uses a temporary file, mytemp.dat , to store data. </li></ul><ul><li>The program creates mytemp.dat if it does not exist and writes 10 random </li></ul><ul><li>integers into mytemp.dat. The data in mytemp.dat is in binary format. </li></ul>
  196. 196. Character Classes <ul><li>The classes that handle characters have at the top of their hierarchy, Reader and Writer </li></ul><ul><li>The subclasses branch out to provide specialized functionality. </li></ul><ul><li>FileReader provides functionality for reading streams of characters from files. </li></ul><ul><li>BufferedReader buffers character streams for efficiency </li></ul><ul><li>FileWriter for writing character streams to files. </li></ul><ul><li>PrintWriter for writing character streams. </li></ul>
  197. 197. File Class <ul><li>File class provides functionality for working directly with files in the operating system </li></ul><ul><li>The File class provides overloaded constructors for creating File objects. A File object can be created by giving the name of the file: </li></ul><ul><ul><li>File inputFile = new File(“in.dat”); // Same directory </li></ul></ul><ul><ul><li>File myInputFile = new File(“C:yDirectoryn.dat”); </li></ul></ul><ul><li>A File Object can refer to either a file or directory </li></ul><ul><ul><li>File theDir = new File(“C:yDir”); //File object theDir refers to a directory </li></ul></ul><ul><li>Some File class methods: </li></ul><ul><ul><li>exists() that tests if the named file already exist. </li></ul></ul><ul><ul><li>mkdir( String st ) for creating directories </li></ul></ul><ul><ul><li>list() for listing the contents of directories </li></ul></ul><ul><ul><li>getPath() gets the path of the named file </li></ul></ul><ul><ul><li>length() returns the file size in bytes </li></ul></ul>
  198. 198. File Class <ul><li>Example: DirectoryContents.java listing the contents of a directory using File class </li></ul><ul><li>import java.io.*; </li></ul><ul><li>public class DirectoryContents </li></ul><ul><li>{ </li></ul><ul><li> public static void main(String[ ] args) </li></ul><ul><li>{ </li></ul><ul><li>File myDir = new File(“C:amp;quot;); </li></ul><ul><li>if(myDir.isDirectory( ) ) { </li></ul><ul><li>System.out.println(&quot;Contents of directory &quot; + myDir ); </li></ul><ul><li>String[ ] contents = myDir.list(); </li></ul><ul><li> for( int I = 0; I < contents.length; I++) </li></ul><ul><li>System.out.println(contents[ I ] ); </li></ul><ul><li>} // End of “if” block </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class DirectoryContents </li></ul>
  199. 199. Using Java I/O <ul><li>Many of the methods including constructors of Java.io classes throw exceptions: </li></ul><ul><li>The most commonly thrown is IOException. </li></ul><ul><li>Reading data from the keyboard </li></ul><ul><ul><li>BufferedReader in </li></ul></ul><ul><ul><li>= new BufferedReader(new InputStreamReader(System.in); </li></ul></ul><ul><ul><li>An InputStreamReader is like an adapter, it reads byte streams and converts it into character streams </li></ul></ul><ul><ul><li>BufferedReader wraps the InputStreamReader to provide extra functionality, allowing to buffer the input to support readLine() </li></ul></ul>
  200. 200. Using Java I/O <ul><li>Example Reading strings from the keyboard </li></ul><ul><li>Import java.io.* </li></ul><ul><li>public class ReadStringFromKeyboard { </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>{ // Converts from bytes to characters </li></ul><ul><li>BufferedReader in = new BufferedReader(new InputStreamReader (System.in)); </li></ul><ul><li>String yourInput; </li></ul><ul><li>try { </li></ul><ul><li>System.out.println(&quot;Please enter any string and hit the return key when done:&quot;); </li></ul><ul><li>yourInput = in.readLine( ); </li></ul><ul><li>System.out.println(&quot; Below is the input you entered&quot;); </li></ul><ul><li>System.out.println(yourInput); </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) { System.out.println(“Could not read from the keyboard” } </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class ReadStringFromKeyboard </li></ul>
  201. 201. Using Java I/O <ul><li>Example: Reading from an external file </li></ul><ul><li>public class ReadFromFile { </li></ul><ul><li>public static void main(String[ ] args) </li></ul><ul><li>{ </li></ul><ul><li> String st = null; </li></ul><ul><li>File inputFileName = null; </li></ul><ul><li>FileReader inputFile = null; </li></ul><ul><li>BufferedReader in = null; </li></ul><ul><li>try { </li></ul><ul><li> inputFileName = new File(&quot;Input1.txt&quot;); </li></ul><ul><li> inputFile = new FileReader(inputFileName); </li></ul><ul><li>in = new BufferedReader(inputFile); </li></ul><ul><li> /* Note: The above 3 lines can be combined in one line as below </li></ul><ul><li>in = new BufferedReader(new FileReader(new File(&quot;Input1.txt&quot;))); */ </li></ul>
  202. 202. Using Java I/O <ul><li>Example Continued </li></ul><ul><li>// Now let us start reading from the opened file </li></ul><ul><li>while((st = br.readLine()) != null ) </li></ul><ul><li> { </li></ul><ul><li> System.out.println(st); // Print the string </li></ul><ul><li>} </li></ul><ul><li> } </li></ul><ul><li>catch (FileNotFoundException fnex) </li></ul><ul><li>{ System.out.println(“Error: “ + fnex.getMessage( ) ); </li></ul><ul><li>System.out.println(&quot;Input file was not found&quot;); </li></ul><ul><li>} </li></ul><ul><li> catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) ); </li></ul><ul><li> System.out.println(&quot;There was a problem reading from the file&quot;); </li></ul><ul><li>} </li></ul>
  203. 203. Using Java I/O <ul><li>Example continued </li></ul><ul><li>finally </li></ul><ul><li>{ </li></ul><ul><li>if( br != null) </li></ul><ul><li>try { </li></ul><ul><li>br.close( ); // Close the file </li></ul><ul><li>} </li></ul><ul><li>catch (Exception ex) { </li></ul><ul><li>System.out.println(“Error: “ + ex.getMessage( ) ); </li></ul><ul><li>System.out.println(&quot;There was a problem with closing the file&quot;); </li></ul><ul><li>} </li></ul><ul><li>} // End finally block </li></ul><ul><li>} // End of main method </li></ul><ul><li>} // End of class </li></ul>
  204. 204. Print Streams <ul><li>The data output stream outputs a binary representation of data, so you cannot view its contents as text. </li></ul><ul><li>In Java, you can use print streams to output data into files. These files can then be viewed as text. </li></ul><ul><li>The PrintStream and PrintWriter classes provide the functionality for doing this. </li></ul><ul><li>PrintStream is for bytes </li></ul><ul><li>PrintWriter is for characters (Unicode) </li></ul>
  205. 205. Print Streams: PrintWriter Constructors <ul><li>PrintWriter(Writer out) </li></ul><ul><li>PrintWriter(Writer out, boolean autoFlush) </li></ul><ul><li>PrintWriter(OutputStream out) </li></ul><ul><li>PrintWriter(OutputStream out, boolean autoFlush) </li></ul>
  206. 206. Print Streams: PrintWriter Methods (for chars) <ul><li>void print(Object o) </li></ul><ul><li>void print(String s) </li></ul><ul><li>void println(String s) </li></ul><ul><li>void print(char c) </li></ul><ul><li>void print(char[] cArray) </li></ul><ul><li>void print(int i) </li></ul><ul><li>void print(long l) </li></ul><ul><li>void print(float f) </li></ul><ul><li>void print(double d) </li></ul><ul><li>void print(boolean b) </li></ul>
  207. 207. Print Streams: PrintWriter Methods <ul><li>Note: </li></ul><ul><li>On the previous slide, you may replace print with println in the various method definitions. </li></ul><ul><li>The println method, which prints the object, is followed by a new line. </li></ul><ul><li>When the object is passed to print or println , </li></ul><ul><li>the object’s toString( ) method converts it to a String object. </li></ul>
  208. 208. Demo Program Example Using Print Streams <ul><li>The next sample Java program creates a print stream, pw , of PrintWriter , wrapped on FileOutputStream , for text format. </li></ul><ul><li>pw = new PrintWriter(new FileOutputStream(tempFile),true); </li></ul><ul><li>The program creates the file, arg[0], if that file does not already exist. </li></ul><ul><li>The program writes 10 random integers into the file by using the data output stream, then closes the stream. </li></ul><ul><li>The data file could be viewed by using the type command in DOS </li></ul>
  209. 209. Using Pri
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×