chapter 6 managing input output files n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 6 Managing Input/Output Files PowerPoint Presentation
Download Presentation
Chapter 6 Managing Input/Output Files

Loading in 2 Seconds...

play fullscreen
1 / 48

Chapter 6 Managing Input/Output Files - PowerPoint PPT Presentation


  • 149 Views
  • Uploaded on

Chapter 6 Managing Input/Output Files. Overview of I/O Streams. Limitations with memory: Storage is temporary It is difficult to handle large volume of data using variables and arrays. File is a collection of related records placed in particular area on disk. Record Field

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

Chapter 6 Managing Input/Output Files


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
    Presentation Transcript
    1. Chapter 6Managing Input/Output Files

    2. Overview of I/O Streams • Limitations with memory: • Storage is temporary • It is difficult to handle large volume of data using variables and arrays. • File is a collection of related records placed in particular area on disk. • Record • Field • File processing in java includes the following processes: • Creating a file • Updating a file • Manipulating data • Reading and writing of data in a file can be done at the level of byte, character, fields or objects.

    3. Streams • Stream is a unidirectional path along which data flows. • Stream represent uniform, easy to use, object oriented interface b/n the program and I/O devices. • Java streams are classified into two basic types: • Input stream • Output stream • Input Stream • To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information sequentially, as shown here:

    4. Output stream • Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially, like this: • While reading/writing /the program does not know any detail about the device. • No matter where the data is coming from or going to and no matter what its type, the algorithms for sequentially reading and writing data are basically the same:

    5. A L G O R I T H M S Reading open a stream while more information read information close the stream Writing Open a Stream while more information write information close the stream • The java.iopackage contains a collection of stream classes that support these algorithms for reading and writing. • To use these classes, a program needs to import the java.io package. • The stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate. • Character Stream classes • Byte Streams Classes

    6. Java Stream Classes Byte Stream Classes Input Stream Classes Output Stream Classes Character Stream Classes Writer Classes Fig : Stream Class hierarchy Reader Classes Java Streams Hierarchies

    7. Standard I/O Streams(predefined streams) • There are three I/O streams predefined and always open for any java program. • System.in:-Input Stream connected to the keyboard. • System.out:-Output Stream connected to output devices. • System.err:-Output stream connected to output devices. • System.out • System.err • Base classes • java.io.InputStream • Java.io.OutputStream • Java.io.Reader • Java.io.Writer Are Outputstreams Both are abstract classes of Byte Stream Reader and Writer are both abstract classes of Character Stream

    8. Byte Stream classes • Byte streams provide a convenient means for handling input and output of bytes. • InputStream and OutputStream classes are abstract Supperclasses representing input and Output Stream of bytes. InputStream FileInputStream FilterInputStream DataInputStream Fig. Partial Inheritance diagram for byte Streams/instream/

    9. Byte Stream … OutputStream • To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStreamand OutputStream. • These streams are typically used to read and write binary data such as images and sounds. • Two of the byte stream classes, ObjectInputStream and ObjectOutputStream, are used for object serialization. These classes are covered in Object Serialization. FileOutputStream FilterOutputStream DataOutputStream PrintStream Fig. partial inheritance diagram for bytes stream/output stream/

    10. Object • The following figure depicts the inheritance hierarchy of the byte stream class. InputStream and OutputStream provide specialized I/O that falls into two categories, data sink streams (shaded) and processing streams (unshaded).

    11. Character Stream Classes • Reader and writer classes support essentially same operations as inputStream and OutputStream, except that their methods operate on character arrays and Strings. • Readerand Writer are the abstract superclasses for character streams in java.io. • Reader provides the API and partial implementation for readers streams that read 16-bit characters and Writer provides the API and partial implementation for writers--streams that write 16-bit characters. • Character streams provide a convenient means for handling input and output of characters. They use Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte streams.

    12. Object Character Stream Class… Fig : Character Stream Class hierarchy

    13. Character Stream Class… • Subclasses of Reader and Writer implement specialized streams and are divided into two categories: those that read from or write to data sinks (shown in gray in the previous slide figure) and those that perform some sort of processing (shown in white). • Most programs should use readers and writers to read and write textual information. The reason is that they can handle any character in the Unicode character set, whereas the byte streams are limited to ISO-Latin-1 8-bit bytes.

    14. Character Stream Class… Reader inputStreamReader BufferedReader FileReader inputStreamReader-from file BufferedReader-from output device OutputStreamWriter-to a file PrintWriter-to attached device/screen Writer OutputStreamWriter PrintWriter FileWriter Fig. partial inheritance model for character streams/reader and writer/

    15. ByteStream • Java.io package contains two important abstract classes for byte streams, inputStream and OutputStream. • The inputStream • Although InputStream is an abstract class, there are many important methods defined in this class. • Important methods • public int read();/*read one byte,return -1 at end of stream*/ • public int read(byte b[]);/*read uptob.length of data from this input stream into an array of bytes. • -return the number of bytes read. • -return -1 if end of stream reached. */ • public int read(byte b[],intoffset,intlen); • /* read up to len bytes of data from this input stream into an array of bytes b Starting at b[offset].*/

    16. ByteStream… • public void close();// closes the input stream. • reset();/*move the current reading position to the mark() set position*/ • mark(intreadLimit);//mark current reading position • The OutputStream • The java.io.OutputStream class sends raw bytes of data to a target, such as the consol or network server. • Like inputStream, OutputStream is an abstract class. • OutputStream methods • public void write(int b);//write a byte to Output stream • public void write(byte buf[]);/*write the data in buf into output stream.*/

    17. ByteStream… • public void write(byte buff[],intoffset,intlen); /* start from offset length len. */ • flush(); /*output all in the buffer */ • Close(); // close output stream • File input stream • FileInputStream is a subclass of inputStream. • Opening a FileInputStream • To open a FileInputStream on a file, give either a String or a file object to the constructor. • FileInputStreammyFileStream; • myFileStream=new FileInputStream(“/pathName/fileName.dat”); Passing a string to constructor FileInputStream

    18. ByteStream… File myFile; FileInputStreammyfileStream; Myfile=new File(“/pathName/fileName.dat”); myFileStream=new InputStream(myFile); myFileStream.close();//closing a stream. • File Output Stream. • FileOutputStream is a subclass of OutputStream. To open a file output stream on a file ,pass either a String or a File object as a parameter to a constructor. • Example:- FileOutputStreammyFileStream; myFileStream=new FileOutputStream(“/pathName/fName.dat”);

    19. ByteStream… • As with the inputStream, you can also use as follows. File myFile; FileOutputStreammyFileStream; myFile=new File(“/pathName/fileName.dat”); myFileStream=new FileOutputStream(myFile) • Closing A Stream • myFileStream.close(); • Example:-/* The following command line filter uses the predefined streams System.in and System.out to copy standard input into standard output */

    20. ByteStream… What does this program do?? • EXample1:IO-Stream • import java.io.*; public class CopyIO{ public static void main(String[]args)throws IOException{ Int b; while((b=System.in.read())!=-1) //return an int System.out.write(b);// display the actual input } } Question:-Can you use System.ou.println(b); instead of System.out.write(b);? • Ans.No b/s the first one displays the numeric value/ascii representation/ for the input character but the second one performs some reformation. • Instead you can use type Casting like System.out.println((char)b);

    21. Example2:Writing bytes to standard output-IO stream • /* The following program displays the character representation of a given byte representation. The array contains byte values which are representations of the string “Hello World “.The program outputs on the screen the character representation of the byte values -“Hello World“. */ • import java.io.*; public class WriteSomeStuff{ public static void main(String[]args)throws IOException{ byte[]hello={72,101,108,108,111,32,87,111,114, 108,100,33,10,13}; System.out.write(hello); } } //output : Hello World

    22. Example3:File input-Output-IO Stream • /* the following program performs byte file IO operations • opens an input file and reads the input file • opens an output file and writes on the output file */ • import java.*; public class CopyFile2{ public static void main(String[]args) throws IOException { FileInputStreaminput=new FileInputStream(“group4.txt”); FileOutputStream output=new FileOutputStream(“group3.back”); int size=input.available();//check input data size for(inti=0;i<size;i++) output.write(input.read());//copy to another file input.close(); output.close(); } } }

    23. Example4:To read command line arguments as Filenames explicitly • Example4-Copying a file Using a command line-IO stream • import java.io.*; public class CopyFile{ public static void main(String []args)throws IOException{ FileInputStreamfinput=new FileInputStream(args[0]); FileOutputStreamfoutput=new FileOutputStream(args[1]); int b; while((b=finput.read())!=-1)//while not EOF read file foutput.write(b);//write data to another file finput.close(); Foutput.close(); } }

    24. Character Stream • Character input is done with one of the reader classes. These reader classes have the following methods(+ a number of others) . • public int read()throws IOException • /* return an integer value, or -1 if end of stream */ • public int read(char[]cbuff)throws IOException • /* fills the array with characters and return the number of characters read */ • … … … • public void close()/* close the stream and frees resources associated with the stream */.

    25. Understanding the I/O Superclasses • Reader and InputStream define similar APIs but for different data types. For example, Reader contains these methods for reading characters and arrays of characters: • int read() • int read(char cbuf[]) • int read(char cbuf[], int offset, int length) • InputStream defines the same methods but for reading bytes and arrays of bytes: • int read() • int read(byte cbuf[]) • int read(byte cbuf[], int offset, int length) • Also, both Reader and InputStream provide methods for marking a location in the stream, skipping input, and resetting the current position.

    26. Writer and OutputStream are similarly parallel. Writer defines these methods for writing characters and arrays of characters: • int write(int c) • int write(char cbuf[]) • int write(char cbuf[], int offset, int length) • And OutputStream defines the same methods but for bytes: • int write(int c) • int write(byte cbuf[]) • int write(byte cbuf[], int offset, int length) • All of the streams--readers, writers, input streams, and output streams are automatically opened when created. You can close any stream explicitly by calling its close method. Or the garbage collector can implicitly close it, which occurs when the object is no longer referenced.

    27. PrintWriter • PrintWriter is used to print formatted representation of objects, such as a String object. • To create a printWriter object you need to pass in a writer or OutputStream object. • Example:-PrintWriter out=new PrintWriter(new FileWriter(“myFile.txt”)); • Methods of PrintWriter • public void print(char c);//print a character • public void print(String s);// prints a string • public void print(inti);// prints an integer • public void print(char c); // prints a character

    28. Example 1:- Character IO Example: For character Stream-Using FileWriter and PrintWriter classes • Example:-the following program receives input from the program and saves the message to an output file.---Character Stream • // write a message to a file import java.io.*; public class WriteFile{ PrintWriteroutputFile; FileWriterfWriter; public static void main(String[]args){ try{ fWriter=new FileWriter(“file.txt”); outputFile =new PrintWriter(fWriter); outputFile.println(“This is a message to be saved in the file”); outputFile.close(); }catch(IOException e){System.err.println(“Problem with file!”);} } } Can you rewrite this program using byteStream classes-FileOutputStream and PrintStream??

    29. //example 2 Character Stream • import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File(“group3.txt"); File outputFile = new File(“group4.txt");  FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c;  while ((c = in.read()) != -1) out.write(c);  in.close(); out.close(); } }  

    30. Example 3:- Character IO • /* The following program display the contents of an input file */ • import java.io.*; • public class display{ public static void main(String []args)throws IOException{ //open input/output and setup variables FileReaderfReader=new FileReader(args[0]); PrintWriterfWriter=new PrintWriter(System.out, true); //PrintWriterpWriter=new PrintWriter(Writer.out, boolean); char[]c=new char[4096]; int read=0; //read and print till end of file while((read=fr.read())!=-1) pWriter.write(c,0,read); fReader.close(); pWriter.close(); } }

    31. Assume the following data is saved in a file called stud.txt in a directory “c:Account”.Write a program that reads this file and prints to the output window. • The next program shows how to read the above file.

    32. public class ReadingFromFile { public int Account; public String FirstName; public String LastName; public double Balance; public Scanner input; • public void openFile() // method that enables user to open a file { try { input = new Scanner( new File( "c:\\stud.txt" ) ); } catch ( FileNotFoundExceptionfileNotFoundException ) { System.err.println( "Error opening file. “ +fileNotFoundException ); } // end catch } // end method openFile

    33. public void readRecords() // methods that helps a user to read record from file • { ReadingFromFilerecord = new ReadingFromFile(); • System.out.printf( "%10s%12s%12s%10s\n", "Account", "First Name", "Last Name", "Balance" ); • try {// read records from file using Scanner object • while ( input.hasNext() ) • { record.Account= input.nextInt() ; // read account number • record.FirstName= input.next() ; // read first name • record.LastName= input.next() ; // read last name • record.Balance= input.nextDouble() ; // read balance • System.out.printf( "%10d%12s%12s%10.2f\n", record.Account, record.LastName, record.FirstName, record.Balance ); • } // end while • } // end try

    34. catch ( NoSuchElementExceptionelementException ) { System.err.println( "File improperly formed." ); input.close(); } // end catch catch ( IllegalStateExceptionstateException ) { System.err.println( "Error reading from file." ); System.exit( 1 ); } // end catch } // end method readRecords   // close file and terminate application • public void closeFile() • { if ( input != null ) • input.close(); // close file • } // end method closeFile • } // end class Re 

    35. The class below is the test class (the client class) that uses the above class functionality public class TestIO { public static void main(String[] args) { ReadingFromFile read = new ReadingFromFile (); read.openFile (); read.readRecords (); read.closeFile(); } }

    36. Object Serialization • Object serialization is a process of writing object’s state to a byte stream. • Object serialization lets you take all the data attributes, write them out as an object, and read them back in as an object. • Object serialization is quite useful when you need to use object persistence. • You could actually use FileOuputStreams and FileInputStreams to write each attribute out individually, and then you could read them back in on the other end. • But you want to deal with the entire object, not its individual attributes. You want to be able to simply store away an object or send it over a stream of objects. • Object serialization takes the data members of an object and stores them away or retrieves them, or sends them over a stream.

    37. Writing an object to a file using ObjectOutputStream: • A FileObjectStream is created using object.txt, which is going to be used to store objects. You create ObjectOutputStream using that file. If you want to store on the ObjectOutputStream, you simply call writeObject() and pass it the object. That's it!. The class could have 20 attributes in it or 50 attributes; it doesn't matter. All of those attributes are automatically stored away. • The class information is stored automatically. • Here is the example code: FileOutputSreamfos = new FileOutputStream("object.dat"); ObjectOutputStreamoos = new ObjectOutputStream(fos); YourClassyc = new YourClass(); oos.writeObject(yc);

    38. Reading an object from a file: Example code • Create a FileInputStream using the file object.txt that was written in the previous panel. That file is used as the source for an ObjectInputStream. • You want to read the object, so we call readObject() and the object is read off the file. • The attributes of the YourClass object are filled in with the data we have stored away.ThereadObject() method returns a reference to an Object class object. • You wrote out a YourClass object, so you have to cast the reference to YourClass. • You have to keep track of the order in which you wrote things out. If you stored away a YourClass object, and then you stored away an AnotherClass object, you have to read them back in the same sequence.

    39. Here is the example code: FileInputStreamfis = new FileInputStream ("object.dat"); ObjectInputStreamois = new ObjectInputStream (fis); YourClassyc; yc = (YourClass) ois.readObject(); • Example: Object writing and Reading, Write code for a class called WriteAndReadObject which contains: Account, First Name, Last name, and Balance as instance variable, and two methods: one for writing Objects to a file and the other for reading these objects back to screen. You have to also write a class called Test that uses WriteAndReadObject class.

    40. import java.io.Serializable; • import java.io.*; • import java.io.FileOutputStream; • import java.io.FileInputStream; • import java.io.ObjectOutputStream; • import java.io.ObjectInputStream; • import java.util.Sccaner; •   public class WriteAndReadObjectimplementsSerializable { • public int Account; • public String FirstName= ""; • public String LastName =""; • public double Balance; • private Scanner input;

    41. // method used for saving class data to a text file as object • public void writing() • { try { • ObjectOutputStreamout = new ObjectOutputStream( new FileOutputStream("object.txt")); • Scanner s= new Scanner(System.in); •  for (inti= 1 ; i< 5; i++) • { WriteAndReadObjectr = new WriteAndReadObject(); • System.out.println("Please enter acccount "); • r.Account= s.nextInt(); • System.out.println("Pl ease enter First Name "); • r.FirstName= s.next(); • System.out.println("Please enter Last Name "); • r.LastName= s.next();

    42. System.out.println("Please enter Balance "); • r.Balance= s.nextDouble(); • out.writeObject(r); • } • } // try ends here • catch (IOException e) • { • System.out.println("Error: " + e); } • finally • { out.close();} • }// end of Writing method

    43. // method used to read data from a text file as an object •  public void Reading () • { try { • WriteAndReadObjectr = new WriteAndReadObject(); • ObjectInputStreamread = new ObjectInputStream( new FileInputStream("object.txt")); • r= (WriteAndReadObject) read.readObject(); • while (r!= null) { • System.out.println( r.Account + " " + r.FirstName + " " + r.LastName + " " + r.Balance); • r= ( WriteAndReadObject ) read.readObject(); • } • }

    44. catch (Exception ex) { System.err.println(ex); } Finally { read.close(); } }// end of method }// end of class // the test class • Public class Object IO Test { public static void main(String[] args) { WriteAndReadObjectwr = new WriteAndReadObject(); wr.writing(); wr.Reading(); } }

    45. Example5:Java IOExceptions • Definition:-An Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. • There are many cases where an abnormal condition happen during program execution. • The file you try to open may not exist. • The class you want to load may be missing. • The other end of your network connection may be non-existent. • Methods of handling exceptions • throws IOException—for I/O • try---catch • throw • finally Revise Chapter5-Excepion handling techniques

    46. Example5:Exception handling using the try—catch block import java.io.*; public class ExceptionalHello{ public static void main(String[]args){ try{ System.out.println(“Hello”+args[0]); }catch(Exception e){ System.out.println(“Hello whoever you are”); } } } }

    47. Input/Output Exception • I/O operations may generate I/O related exceptions: • FileNotFoundException • InterruptedIOException • IOException • Each I/O statement or a group of statements must have exception handler. Or the method must declare that it throws exception. try { //I/O statement(s) } catch(ExceptionClass ex){ // statements for handling I/O error }

    48. public void ioMethod(parameters) throws SomeExceptionClass { //body of the method } End of Managing Input/Output Files