1 / 41

Input and Output

Input and Output. Stream Classes Processing External Files Data Streams Print Streams Buffered Streams Text Input and Output on the Console Object Streams. Streams. A stream is an abstraction of the continuous one-way flow of data. Stream Classes.

atkinsonj
Download Presentation

Input and Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Input and Output • Stream Classes • Processing External Files • Data Streams • Print Streams • Buffered Streams • Text Input and Output on the Console • Object Streams

  2. Streams • A stream is an abstraction of the continuous one-way flow of data.

  3. Stream Classes • The stream classes can be categorized into two types: byte streams and character streams. a) The InputStream/OutputStream class is theroot of all byte stream classes. b) The Reader/Writer class is the root of all character stream classes. • The subclasses of InputStream/ OutputStream are analogous to the subclasses of Reader/Writer. • In all, over 40 classes are used to provide input and output.

  4. A) Byte Stream Classes

  5. B) Character Stream Classes

  6. Abstract InputStream Class • abstract int read() throws IOException read the next byte and returns its value, an int in range 0-255; at the end returns -1. • int read(byte[] b) throws IOException Read up to b.length bytes into array b, returns b.length or the number of bytes read, or returns -1 at the end of the stream. • void close() throws IOException • int available() throws IOException Returns the number of bytes that can be read form the input stream. • long skip(long n) throws IOException Skip over and discard n bytes of data from the input stream.

  7. Abstract Reader Class The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation. • abstract int read() throws IOException • int read(char b[]) throws IOException • void close() throws IOException • void skip(long n) throws IOException

  8. Abstract OutputStream Class • abstract void write(int b) throws IOException • void write(byte[] b) throws IOException • void close() throws IOException • void flush() throws IOException

  9. Abstract Writer Class • abstract void write(char b) throws IOException • void write(char[] b) throws IOException • void close() throws IOException • void flush() throws IOException

  10. The File Class • The File class is a wrapper class for the file name. • The File class does not tell us how to read or write information in files. • The File class is used to check properties of files, such as whether the file exists, or is readable, or is updateable.

  11. The File Class • The statement creates a File object: File MyFile = new File(“C:\myData\in.data”); • Methods String getName(); String getPath(); // Get full path of the file String getAbsolutePath(); String getParent(); // // Get the directory that contains the file int getLength(); boolean exists(); boolean canWrite(); boolean canRead(); boolean isDirectory(); boolean isFile(); boolean delete();

  12. Processing External Files You must use file streams to read from or writeto a disk file. • You can use FileInputStream or FileOutputStream for byte streams. • You can use FileReader or FileWriter for character streams.

  13. File I/O Stream Constructors Constructing instances of FileInputStream, FileOutputStream, FileReader, and FileWriter from file names: public FileInputStream(String filenameString); public FileInputStream(File file); public FileOutputStream(String filenameString); public FileOutputStream(File file); public FileReader(String filenameString); public FileReader(File file); public FileWriter(String filenameString); public FileWriter(File file);

  14. Example of File I/O Stream Constructors FileInputStream infile = new FileInputStream("in.dat"); FileInputStream infile = new FileInputStream(file); FileOutputStream outfile = new FileInputStream("in.dat"); FileOutputStream outfile = new FileInputStream(file); FileReader infile = new FileReader("in.dat"); FileReader infile = new FileRader(file); FileWriter outfile = new FileWriter("in.dat"); FileWriter outfile = new FileWriter(file);

  15. ExampleProcessing External Files

  16. Example: Copy External Files import java.io.*; public class CopyFile { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(new File(args[0]); fos = new FileOutputStream(new File(args[1]); while((int r = fis.read() != -1) { fos.write((byte)r); } } // to be continued...

  17. Example: cont. ... catch (FileNotFoundException ex) { ... } catch (IOException ex) { ... } finally { try { if(fis != null) fis.close(); if(fos != null) fos.close(); } catch (IOException ex) { } } }// main }// class

  18. Data Streams for primitive types • The data streams (DataInputStream and DataOutputStream) read and write Java primitive types in a machine-independent fashion • It enables you to write a data file in one machine and read it on another machine that has a different operating system or file structure. • Data streams are wrappers for on existing input and output streams: DataInputStream dis = new DataInputStream(inStream);

  19. DataInputStream Methods • byte readByte() throws IOException • short readShort() throws IOException • int readInt() throws IOException • long readLong() throws IOException • float readFloat() throws IOException • double readDouble() throws IOException • char readChar() throws IOException • boolean readBoolean() throws IOException • String readUTF() throws IOException

  20. DataOutputStream Methods • void writeByte(byte b) throws IOException • void writeShort(short s) throws IOException • void writeInt(int i) throws IOException • void writeLong(long l) throws IOException • void writeFloat(float f) throws IOException • void writeDouble(double d) throws IOException • void writeChar(char c) throws IOException • void writeBoolean(boolean b) throws IOException • void writeBytes(String l) throws IOException • void writeChars(String l) throws IOException • void writeUTF(String l) throws IOException

  21. Example:Using Data Streams

  22. Data I/O Stream Constructors • DataInputStream in = new DataInputStream(inpStream); DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); Creates a data input stream for file in.dat. • DataOutputStream out=new DataOutputStream(outStream); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); Creates a data output stream for file out.dat.

  23. Example:1. Processing Data Streams import java.io.*; public class TestDataStream { public static void main(String[] args) { DataInputStream dis = null; DataOutputStream dos = null; // Construct a temp file File tempFile = new File(“mytemp.dat”); if(tempFile.exists()) System.exit(0); // cont.

  24. Example:2. Processing Data Streams // Write data try { dos = new DataOutputStream( new FileOutputStream(tempFile)); for(int i=0; i < 10; i++) dos.writeInt((int)(Math.random()*1000)); } catch (IOException ex) { ... } finally { try { if(dos != null) dos.close(); } catch (IOException ex) { } } }

  25. 3. Processing Data Streams try { // Read data dis = new DataInputStream(tempFile); for(int i = 0; i < 0, i++) System.out.println(dis.readInt()); } catch (FileNotFoundException ex) { System.out.println(“File not found.”) } catch (IOException ex) { System.out.println(ex.getMessage()); } finally { try { if(dis != null) dis.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); } } } //method }// class

  26. Print Streams • The data output stream outputs a binary represen-tation of data, so you cannot view its contents as text. In Java, you can use print streams to output data into files. These files can be viewed as text. • The PrintStream and PrintWriter classes provide this functionality.

  27. Buffered Streams • Java introduces buffered streams that speed up input and output by reducing the number of reads and writes. In the case of input, a bunch of data is read all at once instead of one byte at a time. In the case of output, data are first cached into a buffer, then written all together to the file. • Using buffered streams is highly recommended!

  28. Buffered Stream Constructors • BufferedInputStream (InputStream in) // 512 bytes or // chars • BufferedInputStream (InputStream in, int bufferSize) • BufferedOutputStream (OutputStream in) • BufferedOutputStream (OutputStream in, int bufferSize) • BufferedReader(Reader in) • BufferedReader(Reader in, int bufferSize) • BufferedWriter(Writer out) • BufferedWriter(Writer out, int bufferSize)

  29. Buffered Streams: Example BufferedReader infile = null; String inLine; try { infile = new BufferedReader(new FileReader(filename)); while((inLine = infile.readLine()) != null) { System.out.println(inLine); } } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); } catch(IOException ex) { System.out.println(ex.getMessage()); } finally() { try { if(infile != null) infile.close(); } }

  30. Text Input/Output on the Consoles • There are two types of interactive I/O. • One involves simple input from the keyboard and simple output in a pure text form. • The other involves input from various input devices and output to a graphical environment on frames and applets. • The former is referred to as text interactive I/O, and the latter is known as graphical interactive I/O.

  31. Console Output/Input • To perform console output, you can use any of the methods for PrintStream in System.out. • However, keyboard input is not directly supported in Java. In order to get input from the keyboard, you first use the following statements to read a string from the keyboard. (cont’d)

  32. Console Output/Input import java.io.*; public class myInput { /** Read a string from the keyboard */ public static String readString() { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Declare and initialize the string String string = “”; // Get the string from the keyboard try { string = br.getLine(); } catch (IOException ex) { System.out.println(ex); } return string; }

  33. Console Output/Input, cont. /** Read an int value from the keyboard */ public static int readInt() { return Integer.parseInt(readString()); } /** Read a double value from the keyboard */ public static double readDouble() { return Double.parseDouble(readString()); } ... /** Read a character from the keyboard */ public static char readChar() { return readString().charAt(0); } }//class

  34. Object Input and Output • Serializable interface • Object Streams • Example

  35. The Serializable Interface • The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. • Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

  36. The Object Streams • Use the ObjectOutputStream class for storing objects and the ObjectInputStream class for restoring objects. • These two classes are built upon several other classes.

  37. Object Input/Output • import java.io.Serializable; public class MyObject implements Serializable { } . . . • try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(new File(fname))); out.writeObject(myObject); out.close(); } catch(IOException e) { ... } . . . • try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File(fname))); myObject = (MyObject)in.readObject(); } catch(IOException e) { ... }

  38. Example: Write 2D array import java.io.*; import java.io.Serializable; public class WriteMatrix { static double[10][10] data; public static void main(String[] args) { int row = data.length; int col = data[0].length; try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( new File(args[0]))); out.writeObject(data); out.close(); } catch(IOException e) { ... } }//main }//class

  39. Example: Read 2D array import java.io.*; public class ReadMatrix { static double[][] data; public static void main(String[] args) { try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File(args[0]))); data = (double[][])in.readObject(); int row = data.length; int col = data[0].length; } catch(IOException e) { ... } }//main }//class

  40. Example: Write Object import java.io.*; public class WriteMyObject { MyObject obj = new MyObject(); // Object to be stored public static void main(String[] args) { try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(new File(args[0]))); out.writeObject(obj); out.close(); } catch(IOException e) { ... } }//main }//class

  41. Example: Read Object import java.io.*; public class ReadMatrix { static MyObject obj; // Object to be restored public static void main(String[] args) { try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File(args[0]))); obj = (MyObject)in.readObject(); } catch(IOException exc) { ... } }//main }//class

More Related