Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console."— Presentation transcript:

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

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

3 Stream Classes F The stream classes can be categorized into two types: byte streams and character streams. a) The InputStream/OutputStream class is the root 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. F 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 F abstract int read() throws IOException read the next byte and returns its value, an int in range 0- 255; at the end returns -1. F 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 F int available() throws IOException Returns the number of bytes that can be read form the input stream. F 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. F abstract int read() throws IOException F int read(char b[]) throws IOException F void close() throws IOException F void skip(long n) throws IOException

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

9 Abstract Writer Class F abstract void write(char b) throws IOException F void write(char[] b) throws IOException F void close() throws IOException F 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”); F 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 write to 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 Example Processing 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 F 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. F Data streams are wrappers for on existing input and output streams: DataInputStream dis = new DataInputStream(inStream);

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

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

21 Example: Using Data Streams

22 Data I/O Stream Constructors F DataInputStream in = new DataInputStream(inpStream); DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); Creates a data input stream for file in.dat. F 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 F 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. F Using buffered streams is highly recommended!

28 Buffered Stream Constructors F BufferedInputStream (InputStream in) // 512 bytes or // chars F BufferedInputStream (InputStream in, int bufferSize) F BufferedOutputStream (OutputStream in) F BufferedOutputStream (OutputStream in, int bufferSize) F BufferedReader(Reader in) F BufferedReader(Reader in, int bufferSize) F BufferedWriter(Writer out) F 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 F There are two types of interactive I/O. F One involves simple input from the keyboard and simple output in a pure text form. F The other involves input from various input devices and output to a graphical environment on frames and applets. F 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 F Object Streams F 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 F import java.io.Serializable; public class MyObject implements Serializable { }... F try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(new File(fname))); out.writeObject(myObject); out.close(); } catch(IOException e) {... }... F 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


Download ppt "Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console."

Similar presentations


Ads by Google