300 likes | 311 Views
The Java I/O Classes and Interfaces cont’d. Appending to a File. t ry { BufferedWriter out = new BufferedWriter (new FileWriter ( "filename" , true)); out.write ( "aString" ); out.close(); } catch (IOException e) { }. Data streams Stream hierar chy Class: BufferedInputStrea m
E N D
Appending to a File try { BufferedWriter out = newBufferedWriter(new FileWriter("filename", true)); out.write("aString"); out.close(); } catch (IOException e) { }
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
Stream hierarchy Byte streams InputStream FileInputStream DataInputStream OutputStream FileOutputStream DataOutputStream Byte filters FilterInputStream BufferedInputStream DataInputStream FilterOutputStream BufferedOutputStream DataOutputStream
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
Class: BufferedReader public 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. .
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 theresult is -1, then the end of the file stream has beenreached*/
Class: BufferedReader cont’d int inputfile.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 inputfile.read ();//readLine */Read a line from a buffered reader as an integer. file.close ();//Close buffer.
In general, each read request made of aReader causes a corresponding read request to be made of the underlying character or byte stream. • It is therefore advisable to wrap a BufferedReaderaround any Readerwhose read() operations may be costly, such as FileReaders andInputStreamReaders. 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 DataInputStreamwith an appropriate BufferedReader.
Class: BufferedWriter import 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.
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.
Class: FileReader import 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 nrcharacters from a reader and put the result in the specifiedcharacter array. The second argument indicates the element inside thearray where the data's first byte should be stored. The result is the numberof bytes read from the file input stream, or -1 if the end of the stream hasbeen reached.*/
Class: FileWriter import java.io.*; file.close ();// Close writer. FileWriterfile = 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 whether or not characters should be appended to the existingfile. 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 character array. The second argument indicates the element inside thearray 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.*/
Class: BufferedInputStream import java.io.* BufferedInputStream file =new BufferedInputStream(input-stream); //Create a buffered input stream for the specified input stream. BufferedInputStreamfile=new BufferedInputStream(input-streamsize ); /*Create a buffered input stream of the given size for the specified input stream*/ int inputfile.read () /*Read a byte from a buffered input stream. If the result is -1, then the end of the stream has been reached. int inputfile.read ( input-array, first, nr ); /*Read nr bytes from a buffered input stream 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.*/ file.close ();// Close buffer.
Java provides many I/O classes. Next slide provides a summary to make things easier
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-byte conversion dependent on the I/O character encoding being used. • BufferredReader, BufferedWriter, BufferedInputStream, BufferedOutputStream --> to get buffered I/O and to get readLine() method
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)
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.
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); }
// 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 () ;
while ((line = dis.readLine()) != null){ buf.append(line + "\n"); } in.close(); } catch (IOException e ) {} // Load the file into the TextArea. ta.append(buf.toString ()); } }
Class MalformedURLException java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.net.MalformedURLException • Thrown to indicate that a malformed URL has occurred. • Either no legal protocol could be found in a specification string or the string could not be parsed.
toString() Methods • Print 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.
Using toString() Methods Below is a version of CarTest that uses toString() and System.out.println() instead of printing the fields directly and thus works with the new Car class that makes 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); } } }
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 of the class, and names and values of the fields that represent the state of the object, unless there are an excessive number of such fields, in which case only the most important should be returned. • A better Car toString() method would be: public String toString() { return "[Car: plate=" + this.licensePlate + " speed=" + this.speed + + "MaxSpeed=" + this.maxSpeed +"]"); }
Class: File • Files and directories are accessed andmanipulated through the java.io.File class. • Note: the File class does not provide for I/O. Rather it isoften 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");
Class: File cont’d • Another 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
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 separatorFile.separatorChar - char with file separatorFile.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);
Wrappers The 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-bitInputStreamReader 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 methodString 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.