streams file input output i o n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Streams & File Input/Output (I/O) PowerPoint Presentation
Download Presentation
Streams & File Input/Output (I/O)

Loading in 2 Seconds...

play fullscreen
1 / 19

Streams & File Input/Output (I/O) - PowerPoint PPT Presentation


  • 74 Views
  • Uploaded on

Streams & File Input/Output (I/O). Source. Destination. I/O Streams. A java stream is an object consisting of a sequence of bytes that flow from a source to a destination. Stream. Source: A program, a file Destination: Can be a file, the console (i.e. output) window…..

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

PowerPoint Slideshow about 'Streams & File Input/Output (I/O)' - harding-sweeney


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
i o streams

Source

Destination

I/O Streams
  • A java stream is an object consisting of a sequence of bytes that flow from a source to a destination

Stream

  • Source: A program, a fileDestination: Can be a file, the console (i.e. output) window…..
  • We read information from an input stream and write information to an output stream
i o streams1
I/O Streams
  • Streams are a bit of an elusive concept in Java -- it can take a while to get used to them
    • You sort of need to mentally try to picture them over and over again, and the idea of them begins to become clear
  • The java.io.* (input output or I/O for short) package contains many classes that allow us to define various kinds of streams, each with specific characteristics
  • A program can manage multiple streams at a time
  • The I/O package is quite complex and a detailed analysis of all the classes in this package requires practice and experience
i o streams categories
I/O Streams categories
  • There are several categories of I/O streams
  • Today we will limit ourselves to two I/O streams.
  • The first kind of stream deals with reading information from text files.
  • The second deals with writing information to text files.
  • Here are the classes that we will use for each:
    • FileReader: To read lines of text from files
    • PrintWriter: To write lines of text to files
standard i o
Standard I/O
  • We have already dealt with 3 standard I/O streams
    • A standard input stream– defined by System.in
    • A standard output stream – defined by System.out
    • A standard error stream– defined by System.err
  • Yet we never had to create these streams. This is because these streams are very common and are therefore automatically created for us as soon as we start executing a program
streams are objects
Streams are objects:
  • System.out
    • out is a field of the System class.
    • The data type of ‘out’ is a class called PrintStream
      • You could also say that ‘out’ is an object of type PrintStream
    • println is a method of the PrintStreamclass.
  • System.in
    • in is an object of type InputStream
    • readis a method that read only raw byte data
scanner to the rescue
Scanner to the rescue
  • Instead of having to deal with the System.in “rawness” we were able to use a Scanner object

Scannerconsole = new Scanner (System.in);

  • And the handy methods like next(), nextInt(), nextDouble() etc. to read from the console
  • Today we will see how to use Scanner to read from a text file
reading from files
Reading from files
  • Instead of using System.in (i.e. the terminal keyboard) as our input source, we need to create an input source linked to a text file
  • To do this, we need a special stream class, called FileReader
  • The FileReader class has methods that will connect the Scanner class to a specific text file which can then be read
reading from files1
Reading from files

The Scanner class has a very convenient method called nextLine() that reads in a line from a text file.

So, once we have linked the Scanner class to an input file, we can use the nextLine() method to read in each line of the file

The nextLine() method returns a String containing the first line of the file.

The method also positions the cursor at the beginning of the next line

slide10

import java.util.*;

import java.io.*;

public static void main(String[] args)

{

}

throws FileNotFoundException

FileReader dataFile = new FileReader("data.txt");

);

ScannerfileIn = new Scanner(dataFile);

while (fileIn.hasNextLine())

{

}

String aLine =fileIn.nextLine();

System.out.println(aLine);

fileIn.close();

the four steps of file reading
The four steps of file reading

Import the necessary packages (java.io.*)

Create an input stream to the input source:

  • FileReader object to the actual file
  • Scanner associated to the FileReader

Use the appropriate methods to read the data: nextLine() , nextInt(), etc.

Close the stream: fileIn.close()

file i o can generate exceptions
File I/O Can Generate Exceptions

If the program doesn’t find the file or if the file is somehow protected and denies access, the program will throw an exception and abort (crash)

Every time you use FileReader you need to either handle or throw the exception or it will not compile

We can handle by enclosing the I/O code inside a try/catch sequence.

Or, we can simply throw (delegate) with:

throws FileNotFoundException

slide13

import java.util.*;

import java.io.*;

public static void main(String[] args)

{

}

throws FileNotFoundException

FileReader dataFile = new FileReader(“data.txt”);

ScannerfileIn = new Scanner( dataFile);

while (fileIn.hasNextLine())

{

}

String aLine =fileIn.nextLine();

System.out.println(aLine);

fileIn.close();

the four steps of file reading1
The four+ steps of file reading

Import the necessary packages (java.io.*)

Create an input stream to the input source:

  • FileReader object to the actual file
  • Scanner associated to the FileReader

Use the appropriate methods to read the data: nextLine() , nextInt(), etc.

Close the stream: fileIn.close()

Handle or throw the FileNotFoundException

writing to a file
Writing to a file

We need to create an output stream that is connected to a file

For this, we do not use FileReader and Scanner

We make use of the PrintWriter stream class and its methods

slide16

import java.util.*;

import java.io.*;

public static void main(String[] args)

{

}

throws FileNotFoundException

PrintWriter fileOut = new PrintWriter("data.txt");

String aLine = "A line of text";

fileOut.println(aLine);

fileOut.close();

the four steps of file writing
The four+ steps of file writing

Import the necessary packages (java.io.*)

Create an output stream to the output source:

  • PrintWriter object to the actual file

Use the appropriate methods to write the data: println() , print(), etc.

Close the stream: fileOut.close()

important
Important:

What happens when a program attempts to open a file that does not yet exist depends on whether it is for input or output

  • For input: If the file does not exist, an exception will be thrown and the program will stop
  • For output: If the file does not exist PrintWriter will create the file and not throw an exception
    • If the output file already exists, then the PrintWriter object will overwrite the file that was previously there!
printing to file
Printing to file

When PrintWriter writes to an existing file, it overrides whatever is already there, e.g. it does not append

So if you do not want to lose what you already have you should:

  • store the existing data in memory, then
  • write the old and the new using PrintWriter