30
The Java I/O Classes and Interfaces cont’d

The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Embed Size (px)

Citation preview

Page 1: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

The Java I/O Classes and Interfaces

cont’d

Page 2: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Appending to a File

try {

BufferedWriter out = new BufferedWriter (new

FileWriter ("filename", true));

out.write ("aString");

out.close(); }

catch (IOException e)

{

}

Page 3: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Data streams Stream hierarchy Class: BufferedInputStream Class: BufferedOutputStream Class: BufferedReader Class: BufferedWriter Class: DataInputStream Class: DataOutputStream Class: FileInputStream Class: FileOutputStream Class: FileReader Class: FileWriter Class: File

Page 4: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Stream hierarchyByte streams InputStream

FileInputStream DataInputStream

OutputStream FileOutputStream DataOutputStream

Byte filters FilterInputStream

BufferedInputStream DataInputStream

FilterOutputStream BufferedOutputStream DataOutputStream

Page 5: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Stream hierarchy(cont’d)

Character streams Reader

InputStreamReader FileReader

Writer OutputStreamWriter

FileWriter

Character filters BufferedReader (creates a buffered character streamusing a default buffer size.) BufferedWriter

Page 6: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: BufferedReaderpublic class BufferedReader extends Reader Read text from a character-input stream,

buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The buffer size may be specified, or the default size may be used.

The defaults large enough for most purposes.

.

Page 7: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: BufferedReader

import java.io.*;

BufferedReader file = new BufferedReader ( reader );//new (constructor)//Create a buffered reader for the specified reader.

BufferedReader file = new BufferedReader ( reader, size );/*Create a buffered reader of the given size for the specified

reader.*/

char input file.read ();/*Read a character from a buffered reader as an integer. If the

result is -1, then the end of the file stream has been reached*/

Page 8: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: BufferedReader cont’d

int input file.read ( input-array, first, nr );

/*Read nr characters from a buffered reader and put the result in the specified array. The second argument indicates the element inside the array where the data's first byte should be stored. The result is the number of bytes read from the file input stream, or -1 if the end of the stream has been reached.*/

string input file.read (); //readLine

*/Read a line from a buffered reader as an integer.

file.close (); //Close buffer.

Page 9: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.

It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.

For example:BufferedReader in = new BufferedReader (new FileReader ("foo.in")); will buffer the input from the specified file.

Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be

localized by replacing each DataInputStream with an appropriate BufferedReader.

Page 10: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: BufferedWriterimport java.io.*;BufferedWriter file = new BufferedWriter

( writer );//Create a buffered writer for the specified writer.BufferedWriter file=new BufferedWriter(writer,

size );/*Create a buffered writer of the given size for the

specified writer*/file.write ( integer );//Write a character to a buffered writer as an

integer.

Page 11: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: BufferedWritercont’d

file.write ( output-array, first, nr );/*Write nr characters to a buffered writer and read from the

specified character array. The second argument indicates the element inside the array where the data's first character should be stored.*/

file.write ( "string", first, nr );/*Write nr characters to a buffered writer and read from the

specified string. The second argument indicates the element inside the array where the data's first character should be stored.*/

file.newLine (); //Write a new line.

file.close (); //Close buffer.

Page 12: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: FileReaderimport java.io.*;

file.close (); //Close reader.FileReader file = new FileReader ( "filename" );//Create a file reader for the specified file.

char input file.read ();/*Read a character from a reader as an integer. If the result is -1, then the end of the file stream has been reached.*/

int input file.read ( input-array, first, nr );/*Read nr characters from a reader and put the result in thespecified character array. The second argument indicates theelement inside the array where the data's first byte should bestored. The result is the number of bytes read from the file inputstream, or -1 if the end of the stream has been reached.*/

Page 13: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: FileWriterimport java.io.*;file.close (); // Close writer.FileWriter file = new FileWriter ( "filename" );//Create a file writer for the specified file.FileWriter file = new FileWriter ( "filename", boolean );//Create a file writer for the specified file. The boolean indicates

whetheror not characters should be appended to the existing file.file.write ( integer ); //Write a character to a file writer.file.write ( output-array, first, nr );/*Write nr characters to a file writer from the specified characterarray. The second argument indicates the element inside the

array where the data's first byte should be read from.*/file.write ( "string", first, nr )/*Write nr characters to a file writer from the specified string. The

second argument indicates the element inside the array where the data's first byte should be read from.*/

Page 14: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: BufferedInputStreamimport java.io.*

BufferedInputStream file =new BufferedInputStream(input-stream);

//Create a buffered input stream for the specified input stream.

BufferedInputStream file=new BufferedInputStream(input-stream size );

/*Create a buffered input stream of the given size for the specified input stream*/

int input file.read ()/*Read a byte from a buffered input stream. If the result is -1, thenthe end of the stream has been reached.

int input file.read ( input-array, first, nr );/*Read nr bytes from a buffered input stream and put the result in the specifiedarray. The second argument indicates the element inside the array where thedata's first byte should be stored. The result is the number of bytes read fromthe file input stream, or -1 if the end of the stream has been reached.*/file.close (); // Close buffer.

Page 15: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Java provides many I/O classes.

Next slide provides a summary

to make things easier

Page 16: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Java provides

low-level byte-oriented I/O, higher level char I/O, primitive-type I/O, object I/O. I/O objects can be connected into pipes.

FileInputStream, FileOutputStream --> byte oriented I/O (8-bit) InputStreamReader, OutputStreamWriter --> Character I/O (16-

bit) these are built on top of byte oriented I/O through a char-to-byteconversion dependent on the I/O character encoding being used. BufferredReader, BufferedWriter, BufferedInputStream,

BufferedOutputStream --> to get buffered I/O and to get readLine() method

Page 17: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

PrintStream, PrintWriter --> output string representation of primitive and object types

RandomAccessFile --> file updating, appending

DataInputStream, DataOutputStream --> primitive type binary I/O

ObjectInputStream, ObjectOutputStream --> serializable object binary I/O

Unicode can use different encodings: UTF-16, UTF-16BE, UTF-16LE, UTF-8, US-ASCII (7-bit)

Page 18: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Example: Reading a File from an Applet

Page 19: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

We use the URL class that is convenient for accessing web resources.

This class provides various methods and fields, e.g. separate fields for the domain, path and file, that can be useful.

URL class also provides a method to obtain file access through an InputStream.

We can wrap this stream with an InputStreamReader to provide proper character handling.

aBufferedReader is wrapped around the stream to provide buffering to smooth out the stream flow and also to get the readLine() method for grabbing a whole line at once and returning it in a string.

Page 20: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

import java.applet.*; import java.awt.*; import java.io.*; import java.net.*; public class ReadFile extends Applet {   StringBuffer buf; String FileToRead ="message.txt"; TextArea ta; //--------------------------------------------------------

  public void init() {     ta = new TextArea(40, 40);

  ta.setEditable(false);  setLayout (new BorderLayout());

   add(ta, "Center");     // Get setup parameters from applet html

    String param = getParameter ("FileToRead");     if ( param != null) {       FileToRead = new String (param);     }      

Page 21: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

// Now read the file.     readFile();   }

public void readFile(){     String line;     URL url = null;

   try {      url = new URL (getCodeBase(), FileToRead );     }     catch (MalformedURLException  e ) {        System.out.println ("Malformed URL ");       stop();     }       try {       InputStream in= url.openStream();       BufferedReader dis = new BufferedReader (new

InputStreamReader(in));       buf = new StringBuffer () ;    

Page 22: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

   while ((line = dis.readLine()) != null){          buf.append (line + "\n");       }

      in.close();     }     catch (IOException e ) { }     // Load the file into the TextArea.     ta.append(buf.toString ());   } }

Page 23: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class MalformedURLException

java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.net.MalformedURLException

Thrown to indicate that a malformed URL hasoccurred. Either no legal protocol could be found in aspecification string or the string could not be parsed.

Page 24: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

toString() MethodsPrint methods are common in some

languages, but most Java programs operate differently.

You can use System.out.println() to print any object.

However for good results your class should have a toString() method that formats the object's data in a sensible way and returns a string.

Otherwise all that's printed is the name of the class which is normally not what you want.

Page 25: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Using toString() MethodsBelow is a version of CarTest that uses toString() andSystem.out.println() instead of printing the fieldsdirectly and thus works with the new Car class thatmakes its fields private.

class CarTest { public static void main(String args[]) { Car c = new Car ("New York A45 636", 123.45);

System.out.println(c); for (int i = 0; i < 15; i++) { c.accelerate(10.0); System.out.println(c); } } }

Page 26: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Rules for toString() Methods toString() methods should return a single line of text that does

not contain any carriage returns or linefeeds. toString() methods are primarily for debugging. toString() should not do a lot of fancy processing. toString() methods should be quick. The string returned by toString() should contain the name ofthe class, and names and values of the fields that representthe state of the object, unless there are an excessive numberof such fields, in which case only the most important should bereturned. A better Car toString() method would be: public String toString() { return "[Car: plate=" + this.licensePlate + " speed=" + this.speed + + "MaxSpeed=" + this.maxSpeed +"]"); }

Page 27: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: FileFiles and directories are accessed and manipulated

through the java.io.File class.

Note: the File class does not provide for I/O. Rather it is often used in the arguments for the file I/O class methods.

The file instance can be created with a path name:

File fileA = new File("/tmp/filea.txt");

Or relative to the current directory of the interpreter:

   File fileA = new File("filea.txt");

Page 28: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: File cont’dAnother overloaded constructor allows separate

specification of the path and the file name:

  File fileA = new File("/tmp", "filea.txt");

Directories can also be specified:

 File direc = new File("/tmp");

There are a number of useful methods in File, e.g.:

 Boolean exist();          - does the file exist  Boolean canWrite();   - can the file be written to  Boolean canRead();      - can the file be read  Boolean isFile();        - does it represent a file  Boolean isDirectory();- or a directory

Page 29: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

Class: File cont’d There are also methods to get the file name and path

components, to make a directory, to get a listing of the files in a directory, etc.

Note that path names use different separator characters on different hosts. Windows uses "\", Unix"/", Macintosh ":".

The static variables: File.separator - string with file separator

File.separatorChar - char with file separator File.pathSeparator - string with path separatorFile.pathSeparatorChar - char with path separator

can be used to insure one's programs are platform independent

String dirName = "dataDir";String filename = "data.dat";File filData =  new File(dirName + File.separator + filename);

•  

Page 30: The Java I/O Classes and Interfaces cont’d. Appending to a File try { BufferedWriter out = new BufferedWriter (new FileWriter ("filename", true)); out.write

WrappersThe Java I/O framework uses wrapper classes to build specialized I/O streams.Typically an instance of a lower level class is created and then it is wrapped

inside ever more specialized stream instances:...

 // Convert the 8-bit System input to 16-bit InputStreamReader in = new InputStreamReader (System.in);

// Wrap with in a buffer object to speed I/O BufferedReader bufIn = new BufferedReader(in);

.. // Read the keyboard input using the readLine method   String strLine = bufIn.readLine();

Here we wrap an 8-bit character stream with a 16-bit character Reader class.

Buffered classes improve the performance of I/O by providing intermediate buffers to hold data and even out the data flow.