streams and files
Skip this Video
Download Presentation
Streams and Files

Loading in 2 Seconds...

play fullscreen
1 / 45

Streams and Files - PowerPoint PPT Presentation

  • Uploaded on

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

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

PowerPoint Slideshow about ' Streams and Files' - peers

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
  • Stream classes
  • File objects
  • File operations with streams
  • Examples in C++ and Java
file i o
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
C++ Stream class hierarchy (simplified)













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



c disk file i o with streams
C++ Disk file I/O with Streams
  • Three relevant classes:
    • ifstreamfor input // ifstreaminfile;
    • ofstreamfor output // ofstreamoutfile;
    • fstreamfor both input and output // fstreamiofile;
opening and closing a file
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) (”my file”);


reading and writing text files
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
what is needed to use files
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;

open the file
Open the File
  • Open the file
  • Use the open member function"inventory.dat");"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
use the file
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;

close the file
Close the File
  • Close the file
  • Use the close member function



  • 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

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

cout<< “Enter name of output file: “;

cin >> outfileName; (outfileName);



#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main ( ) {



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;



JavaFile I/O

  • Lots of stream classes!!
  • Designed to work with Exceptions/Exception Handling
stream zoo
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.
stream zoo1
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...
stream zoo2
Stream Zoo
  • File processing
    • Import
      • 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
  • 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.

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.
example 2
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).
files and streams
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)
  • Other languages offer niceties such as buffering and lookahead automatically in stream libraries
  • Java’s ability to combine provides greater flexibility
text streams
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.
reader class hierarchy
Reader Class Hierarchy











reader example
Reader - example
  • import*;
  • 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 = != -1; total++){
  • if(Character.isWhitespace((char) ch))
    • spaces++;
  • }
  • System.out.println(total + " chars " + spaces + " spaces ");
  • }
  • }

Count total number of spaces in the file

buffered streams
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.
buffered streams1
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.
bufferedreader example
BufferedReader - example


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 )






  • Use a BufferedReader to read a file one line at a time and print the lines to standard output
writer class hierarchy
Writer Class Hierarchy










text streams1
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

text streams2
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)

{ …


text streams3
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.
text streams4
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.
string tokenizers and delimited text
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

reading delimited input
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());

files and exceptions
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.
  • Each I/O statement or a group of I/O statements much have an exception handler around it/them as follows:



…// I/O statements – open file, read, etc.


catch(IOException e) // or specific type exception


…//message output statements




class CountBytesNew


public static void main (String[] args)

throws FileNotFoundException, IOException // optional in this case


FileInputStream in;



in = new FileInputStream("FileIn.txt");

int total = 0;

while ( != -1)


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




standard input output
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 – and System.out are streams
    • is an InputStream object
    • System.out is an OutputStream object
    • Instantiated by the JVM
files and directories
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.


c file information example
C++ file information example

std::ifstream::pos_typefilesize(const char* filename)


std::ifstream in(filename, std::ifstream::in |


in.seekg(0, std::ifstream::end);

return in.tellg();


random access to files
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.