streams and files cmps 2143. overview stream classes file objects file operations with streams...

45
Streams and Files CMPS 2143

Upload: verity-stevens

Post on 27-Dec-2015

227 views

Category:

Documents


2 download

TRANSCRIPT

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

Streams and Files

CMPS 2143

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

2

Overview

•Stream classes

•File objects

•File operations with streams

•Examples in C++ and Java

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

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

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

C++ Stream class hierarchy (simplified)iosios

iosistream iosostream

iosifstream

iosfstream

iosiostream iosofstream

The classes used specifically for disk file I/O are declared in the file fstream

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

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;

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

Opening and Closing a filevoid 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();

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

7

open (filename, mode);ios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

ios::ateSet 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::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

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

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

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

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;

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

Open the File3. 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

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

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;

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

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

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

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

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

Example#include <iostream>#include <fstream>#include <string>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;}

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

15

• Lots of stream classes!!•Designed to work with Exceptions/Exception Handling

JavaFile I/O

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

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.

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

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

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

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

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

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.

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

20

ExampleFileInputStream 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

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

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

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

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)

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

23

Comparisons•Other languages offer niceties such as buffering and

lookahead automatically in stream libraries• Java’s ability to combine provides greater flexibility

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

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.

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

25

Reader Class Hierarchy

ReaderStringReader

CharacterArrayReader

PipedReader

BufferedReader

FileInputStreamInputStreamReader

FilterReader

FileReaderPushbackReader

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

26

Reader - operationspublic 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

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

27

Reader - exampleCount 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

"); }}

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

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.

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

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.

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

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); }

}}

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

Writer Class Hierarchy

WriterBufferedWriter

CharacterArrayWriter

FilterWriter

PrintWriter

PipedWriterOutputStreamWriter

StringWriter

FileWriter

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

32

Text Streams•For text output, use PrintWriter.▫Can print strings and numbers in text format▫Must be combined with destination writerPrintWriter 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

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

33

Text Streams•No analog to read data in text format.•Only possibility for processing text input is BufferedReaderBufferedReader 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){ …}

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

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.

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

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.

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

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

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

37

Reading Delimited InputbufferedReader 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());

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

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.

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

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}

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

40

Exampleimport 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"); } }}

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

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

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

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

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

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

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

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.

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

45

References

•http://www.cplusplus.com/doc/tutorial/files/•http://tutorials.jenkov.com/java-io/index.html http://do

cs.oracle.com/javase/7/docs/api/