1 / 45

Streams and Files

Streams and Files. CMPS 2143. Overview. Stream classes File objects File operations with streams Examples in C++ and Java. File I /O. A stream is a general name given to a flow of data. Disk file I/O is a special case of the general I/O system. C++ Stream class hierarchy (simplified).

peers
Download Presentation

Streams and 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. 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. Streams and Files CMPS 2143

  2. Overview • Stream classes • File objects • File operations with streams • Examples in C++ and Java

  3. File I/O • A stream is a general name given to a flow of data. • Disk file I/O is a special case of the general I/O system

  4. C++ Stream class hierarchy (simplified) ios ios ios ios ostream istream ios ifstream ios ios iostream ofstream The classes used specifically for disk file I/O are declared in the file fstream ios fstream

  5. C++ Disk file I/O with Streams • Three relevant classes: • ifstreamfor input // ifstreaminfile; • ofstreamfor output // ofstreamoutfile; • fstreamfor both input and output // fstreamiofile;

  6. Opening and Closing a file void ifstream::open(const char *filename, ios::openmode mode= ios::in) void ofstream::open(const char *filename, ios::openmode mode= ios::out | ios::trunc) void fstream::open(const char *filename, ios::openmode mode= ios::in | ios::out) ioFile.open (”my file”); ioFile.close();

  7. open (filename, mode);

  8. Reading and writing Text Files • Use << and >> operators the same way you do when performing console I/O, except that instead of using cin, cout substitue a string that is linked to a file

  9. What is Needed to Use Files • Include the fstream header file • Define a file stream object • ifstream for input from a file ifstream infile; • ofstream for output to a file ofstream outfile;

  10. Open the File • Open the file • Use the open member function infile.open("inventory.dat"); outfile.open("report.txt"); • Filename may include drive, path info. • Output file will be created if necessary; existing file will be erased first • Input file must exist for open to work

  11. Use the File • Use the file • Can use output file object and << to send data to a file outfile << "Inventory report"; • Can use input file object and >> to copy data from file to variables infile >> partNum; infile >> qtyInStock >> qtyOnOrder;

  12. Close the File • Close the file • Use the close member function infile.close(); outfile.close(); • Don’t wait for operating system to close files at program end • May be limit on number of open files • May be buffered output data waiting to be sent to a file

  13. Reading Input from ANY File and Writing Output to ANY File void openFiles (ifstream & infile, ofstream & outfile) { char infileName[40]; char outfileName[40]; //open input and output files cout<< “Enter name of input file: “ ; cin >> infileName; infile.open (infileName); cout<< “Enter name of output file: “; cin >> outfileName; outfile.open (outfileName); }

  14. Example #include <iostream> #include <fstream> #include <string> using namespace std; int main ( ) { ofstreamoutfile; ifstreaminfile; double price, discount, newPrice; //open input and output files openFiles (infile, outfile) //get price and discount infile >> price >> discount; //calculate newPrice newPrice = price * discount; //echoprint input outfile << “Price is $ “ << price << endl; outfile << “Discount is “ << discount <<endl << endl; //display result outfile << “New price is $” << newPrice << endl; //close files infile.close( ); outfile.close( ); return 0; }

  15. JavaFile I/O • Lots of stream classes!! • Designed to work with Exceptions/Exception Handling

  16. Stream Zoo • C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) • Java goes overboard, gives you separate classes for selecting buffering, lookahead, random access, text formatting, zip format, or binary data. • 4 abstract classes at base: • InputStream, OutputStream, Reader and Writer.

  17. Stream Zoo • InputStream and OutputStream deal with bytes • DataInputStream and DataOutputStream deal with basic Java types read in as binary data: • DataInputStreams • Read binary data from InputStream • Methods read, readByte, readChar, readDouble... • DataOutputStreams • Write binary data to OutputStream • Methods write, writeChar, writeInt...

  18. Stream Zoo • File processing • Import java.io • Definitions of stream classesFileInputStreamandFileOutputStream • Inherit fromInputStreamandOutputStream • abstract classes • FileInputStream and FileOutputStream give you streams attached to disk files. • FileInputStream fin = new FileInputStream (“file.dat”) • Only support at byte level

  19. Problem • FileInputStream has no methods to read numeric types • DataInputStream has no methods to get data from a file • Java has creative mechanism to combine two into filtered streams by feeding existing stream to the constructor of another stream.

  20. Example FileInputStream fin = new FileInputStream (“file.dat”); DataInputStream din = new DataInputStream (fin); Double s = din.readDouble ( ); • The newly created filtered stream still accesses data from the file attached to the file input stream, but it now has more capable interface. • NOT BUFFERED

  21. Example 2 • Not buffered: every call to read contacts OS to ask it to dole out another byte. IF you want buffering, data input for a file, you combine 3 types. DataInputStream din = new DataInputStream (new BufferedInputStream (new FileInputStream (“file.dat”))); • Note that DataInputStream is last because we want to use DataInputStream methods (and we want them to use buffered read method).

  22. Files and Streams • Buffering • Improves I/O performance • I/O is slow compared to processor • Buffer stores data of many I/O operations • When full, sends data • Can be explicitly flushed (forced to send data)

  23. Comparisons • Other languages offer niceties such as buffering and lookahead automatically in stream libraries • Java’s ability to combine provides greater flexibility

  24. Text Streams • Set of stream filters that bridges gap between Unicode-encoded text and character encoding used by local OS. • Use classes that descend from Reader and Writer (similar methods to InputStream and OutputStream) • FileReader and FileWriterattach a reader or writer to a file.

  25. Reader Class Hierarchy Reader StringReader CharacterArrayReader PipedReader BufferedReader FileInputStream InputStreamReader FilterReader PushbackReader FileReader

  26. Reader - operations

  27. Reader - example • import java.io.*; • public class CountSpaces{ • public static void main (String[] args) • throws IOException • { • Reader infile; // infilecan also be FileReader • infile = new FileReader("FileIn.txt"); • int ch, total, spaces; • spaces = 0; • for (total = 0 ; (ch = infile.read()) != -1; total++){ • if(Character.isWhitespace((char) ch)) • spaces++; • } • System.out.println(total + " chars " + spaces + " spaces "); • } • } Count total number of spaces in the file

  28. Buffered Streams • Java supports creation of buffers to store temporarily data that read from or written to a stream. This process is known as buffered I/O operation. • Buffered stream classes – BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter buffer data to avoid every read or write going to the stream. • These are used in file operations since accessing the disk for every character read is not efficient.

  29. Buffered Streams • Buffered character streams understand lines of text. • BufferedWriter has a newLine method which writes a new line character to the stream. • BufferedReader has a readLine method to read a line of text as a String. • For complete listing of methods, please see the Java manual/documentation.

  30. BufferedReader - example import java.io.*; class ReadTextFile { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader in; in = new BufferedReader( new FileReader(“Command.txt”)); String line; while (( line = in.readLine()) != null ) { System.out.println(line); } } } • Use a BufferedReader to read a file one line at a time and print the lines to standard output

  31. Writer Class Hierarchy Writer BufferedWriter CharacterArrayWriter FilterWriter PrintWriter PipedWriter OutputStreamWriter StringWriter FileWriter

  32. Text Streams • For text output, use PrintWriter. • Can print strings and numbers in text format • Must be combined with destination writer PrintWriter out = new PrintWriter (new FileWriter (“file.out”)); String name = “Harry Hacker”; double salary = 75000.00; out.print (name); out.print (‘ ‘); out.println (salary); //don’t throw exceptions

  33. Text Streams • No analog to read data in text format. • Only possibility for processing text input is BufferedReader BufferedReader in = new BufferedReader (new FileReader (“descriptions.txt”)); • readLine method • reads a line of text. • Returns null when no more input available String line; while ((line = in.readLine () ) != null) { … }

  34. Text Streams • To read numbers from text input, you need to read a string first, and then convert it. String s = in.readLine ( ); Double x = Double.parseDouble (s); • If more than one number on a line, you must break up the input string Use StringTokenizer utility class.

  35. Text Streams • To read numbers from text input, you need to read a string first, and then convert it. String s = in.readLine ( ); Double x = Double.parseDouble (s); • If more than one number on a line, you must break up the input string Use StringTokenizer utility class.

  36. String Tokenizers and Delimited Text • Must specify delimiters to separate out tokens StringTokenizer t = new StringTokenizer (line, “|”); StringTokenizer t = new StringTokenizer (line, “ \t\n\r”); //white space StringTokenizer t = new StringTokenizer (line); //default is white space

  37. Reading Delimited Input bufferedReader in = new BufferedReader (new FileReader (“file.dat”)); String s = in.readLine ( ); StringTokenizer t = new StringTokenizer (s); String name = t.nextToken (); double Salary = Double.parseDouble (t.nextToken()); int year = Integer.parseInt (t.nextToken());

  38. Files and Exceptions • When creating files and performing I/O operations on them, the system may generate errors. The basic I/O related exception classes are given below: • EOFException – signals that end of the file is reached unexpectedly during input. • FileNotFoundException – file could not be opened • InterruptedIOException – I/O operations have been interrupted • IOException – signals that I/O exception of some sort has occurred – very general I/O exception.

  39. Syntax • Each I/O statement or a group of I/O statements much have an exception handler around it/them as follows: try { …// I/O statements – open file, read, etc. } catch(IOException e) // or specific type exception { …//message output statements }

  40. Example import java.io.*; class CountBytesNew { public static void main (String[] args) throws FileNotFoundException, IOException // optional in this case { FileInputStream in; try { in = new FileInputStream("FileIn.txt"); int total = 0; while (in.read() != -1) total++; System.out.println("Total = " + total); } catch(FileNotFoundException e1) { System.out.println("FileIn.txt does not exist!"); } catch(IOException e2) { System.out.println("Error occured while read file FileIn.txt"); } } }

  41. Standard Input/Output • C++ - cin and cout are streams • cout is an ostream object • cin is an istream object • constructed by ios_base::Init before the body of main begins execution • Java – System.in and System.out are streams • System.in is an InputStream object • System.out is an OutputStream object • Instantiated by the JVM

  42. Files and Directories • Sometimes you may need access to information about a file rather than its content. • For instance, if you need to know the file size or the file attributes of a file. • The same may be true for a directory. • For instance, you may want to get a list of all files in a given directory. • Both file and directory information is available via the File class in Java. infile.length();

  43. C++ file information example std::ifstream::pos_typefilesize(const char* filename) { std::ifstream in(filename, std::ifstream::in | std::ifstream::binary); in.seekg(0, std::ifstream::end); return in.tellg(); }

  44. Random Access to Files • You can get random access to files. • Random doesn't mean that you read or write from truly random places. • It just means that you can skip around the file and read from or write to it at the same time. • This makes it possible to write only parts of an existing file, to append to it, or delete from it.

  45. References • http://www.cplusplus.com/doc/tutorial/files/ • http://tutorials.jenkov.com/java-io/index.html http://docs.oracle.com/javase/7/docs/api/

More Related