Presentation is loading. Please wait.

Presentation is loading. Please wait.

Streams and Files CMPS 2143. Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.

Similar presentations


Presentation on theme: "Streams and Files CMPS 2143. Overview Stream classes File objects File operations with streams Examples in C++ and Java 2."— Presentation transcript:

1 Streams and Files CMPS 2143

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

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 istream ios ostream ios ifstream ios fstream ios iostream ios ofstream The classes used specifically for disk file I/O are declared in the file fstream

5 C++ Disk file I/O with Streams Three relevant classes: ▫ ifstream for input// ifstream infile; ▫ ofstream for output// ofstream outfile; ▫ fstream for both input and output // fstream iofile;

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); ios::in Open for input operations. ios::out Open for output operations. ios::binary Open in binary mode. ios::ate Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file. ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one. 7

8 Reading and writing Text Files Use > 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 1.Include the fstream header file 2.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 3.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 Chapter 3 slide 11 Use the File 4.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 Chapter 3 slide 12 Close the File 5.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 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); } Reading Input from ANY File and Writing Output to ANY File

14 Example #include using namespace std; int main ( ) { ofstream outfile; ifstream infile; 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 Lots of stream classes!! Designed to work with Exceptions/Exception Handling 15 JavaFile I/O

16 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 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 18 Stream Zoo File processing ▫ Import java.io  Definitions of stream classes FileInputStream and FileOutputStream  Inherit from InputStream and OutputStream  abstract classes FileInputStream and FileOutputStream give you streams attached to disk files. ▫ FileInputStream fin = new FileInputStream (“file.dat”) ▫ Only support at byte level

19 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 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 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 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 23 Comparisons Other languages offer niceties such as buffering and lookahead automatically in stream libraries Java’s ability to combine provides greater flexibility

24 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 FileWriter attach a reader or writer to a file.

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

26 26 Reader - operations public int read()Reads a character and returns as a integer 0-255 public int read(char[] buf, int offset, int count) Reads and stores the characters in buf starting at offset. count is the maximum read. public int read(char[] buf)Same as previous offset=0 and length=buf.length() public long skip(long count)Skips count characters. public boolean()Returns true if the stream is ready to be read. public void close()Closes stream

27 27 Reader - example Count total number of spaces in the file import java.io.*; public class CountSpaces { public static void main (String[] args) throws IOException { Reader infile; // infile can 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 "); }

28 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 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 30 BufferedReader - example Use a BufferedReader to read a file one line at a time and print the lines to standard output 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); }

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

32 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 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 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 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 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 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 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 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 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 41

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(); 42

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

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. 44

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/ http://tutorials.jenkov.com/java-io/index.html http://docs.oracle.com/javase/7/docs/api/ 45


Download ppt "Streams and Files CMPS 2143. Overview Stream classes File objects File operations with streams Examples in C++ and Java 2."

Similar presentations


Ads by Google