[go: up one dir, main page]

0% found this document useful (0 votes)
126 views16 pages

Java OOp I - O Straeming

This document discusses input/output (I/O) streaming in Java. It explains that I/O streaming allows data to be read from and written to files and other external sources. It covers the key classes in Java's java.io package for implementing I/O streams, including InputStream, OutputStream, Reader and Writer. It provides examples of reading from keyboard input and writing to an output file using PrintStream. The document also discusses byte streams for binary data versus character streams for text, and the steps to use stream classes which include opening, reading/writing, and closing a stream.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views16 pages

Java OOp I - O Straeming

This document discusses input/output (I/O) streaming in Java. It explains that I/O streaming allows data to be read from and written to files and other external sources. It covers the key classes in Java's java.io package for implementing I/O streams, including InputStream, OutputStream, Reader and Writer. It provides examples of reading from keyboard input and writing to an output file using PrintStream. The document also discusses byte streams for binary data versus character streams for text, and the steps to use stream classes which include opening, reading/writing, and closing a stream.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

CHAPTER SIX

FILE MANAGEMENT
INPUT/OUTPUT BASICS
I/O Streaming
Why I/O Streaming?
Data stored in variables and arrays is temporary- it’s lost when a local variable goes out of scope or when
the program terminates.
For long-term retention of data, even after the programs that create the data terminate, computers use
files.
You can write data to a file instead of the computer screen.
You can write certain data to a file while still putting other data on the screen or you may want to query
the user for input rather than accepting it all on the command line.
Or maybe you want to read data out of a file that's in a particular format.
In Java all these methods take place as streams using File I/O streams.
The System.out.println() statement we've been using all along is an implementation of Streams.
In order to use the Java file classes, we must import the Java Input/Output package (java.io) in the following
manner import java.io.*;
I/O Streaming
Reading and Writing with Java's Input / Output Streams
Input/Output = I/O = communication between a computer program and external sources and
destinations of information
Involves reading and writing
Reading input from a source
Writing output to a destination

Example sources and destinations are: Files, Network connections, Other programs
Java uses an I/O system called streams (pioneered in C++)
Java provides java.io package to implement streams
Streams treat all external source and destinations of data the same way: as "streams" of information
Input Vs. Output Streams

• READING FROM AN INPUT STREAM

• WRITING TO AN OUTPUT STREAM


I/O Streaming
Byte vs. Character Streams
• Byte streams are used to read and write data in binary format (1's and 0's)
Example data: images, sounds, executable programs, word-processing documents, etc.
• Character streams are used to read and write data in text format (characters)
Example data: plain text files (txt extension), web pages, user keyboard input, etc.

I/O Streaming Java Classes


• Package java.io offers classes to connect to streams.
• To connect to a stream, instantiating a subclass of one of these abstract super classes is required:
Input Output
Byte InputStream OutputStream
Character Reader Writer
I/O Streaming
Steps to use any Stream classes
1. Open a stream by instantiating a new stream object
2. While there is more information to read/write, read/write that data
3. Close the stream by calling the object’s close() method
Reading from Keyboard Input
Keyboard input is sent over a stream referred to as "Standard" input
Java “Standard" input is the InputStream object System.in (a byte stream)
To read characters over an InputStream, need to wrap it in an InputStreamReader.
To read line by line, wrap the InputStreamReader WITH A BufferedReader.
Reading from keyboard input
/**
* Returns a line read from keyboard input.
* Return null if there was an error reading the line.
*/
public String readKeyboardLine() throws IOException {
BufferedReader br = null;
String line = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
line = br.readLine();
} catch (IOException e) {}

if (br != null) {
try { br.close(); }
catch (IOException e) { /* ignore */ }
}

return line;
}
I/O Streaming
Example : Write the Fahrenheit to Celsius table in a file
while (fahr <= upper) {
import java.io.*; // while loop begins here
class FahrToCelsius { celsius = 5.0 * (fahr-32.0) / 9.0;
public static void main (String args[]) { myOutput.println(fahr + " " + celsius);
double fahr, celsius; fahr = fahr + step;
double lower, upper, step;
} // while loop ends here
lower = 0.0; // lower limit of temperature table
} // try ends here
upper = 300.0; // upper limit of temperature table
catch (IOException e) {
step = 20.0; // step size System.out.println("Error: " + e);
fahr = lower; }
try { } // main ends here
FileOutputStream fout = new }//End Class
FileOutputStream("c:\\test.out");

PrintStream myOutput = new PrintStream(fout); // now the


//FileOutputStream into a PrintStream
I/O Streaming
There are only three things necessary to write formatted output to a file rather than to the standard
output:
1. Open a FileOutputStream using a line like
FileOutputStream fout = new FileOutputStream("c:\\test.out");
This line initializes the FileOutputStream with the name of the file you want to write into.
2. Convert the FileOutputStream into a PrintStream using a statement like
PrintStream myOutput = new PrintStream(fout);
The PrintStream is passed the FileOutputStream from step 1.
3. Instead of using System.out.println() use myOutput.println().
System.out and myOutput are just different instances of the PrintStream class. To print to a different
PrintStream we keep the syntax the same but change the name of the PrintStream.
I/O Streaming
Reading data from a Text File
The following code reads user information from a file and then prints to the standard output in the
order they were listed. Assume that the following data was saved in amu.txt file

Account First Name Last Name Balance


100 Bob Jones 24.98
200 Steve Doe -345.67
300 Pam White 0.00
400 Sam Stone -42.16
500 Sue Rich 224.62
I/O Streaming
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ReadingFromFile {
public int account;
public String firstName,lastName;
public double balance;
public Scanner input;
I/O Streaming
public void openFile(){ //method to open a file
try {
input = new Scanner(new File(“C:\\amu.txt"));
}catch (FileNotFoundException fnfe )
{ System.err.println(“Error opening file. “ +fnfe ); } // end of catch
} // end method openFile

public void readRecords() { // method to read record from file


ReadingFromFile record = new ReadingFromFile(); // object to be written to screen
System.out.printf( "%10s%12s%12s%10s\n", "account", "first name", "last name",
"balance" );
I/O Streaming
try { // read records from file using scanner object
while ( input.hasNext() ){

record.account= input.nextInt() ; // read account number


record.firstName= input.next() ; // read first name
record.lastName= input.next() ; // read last name

record.balance= input.nextDouble() ; // read balance


// display record content
System.out.printf( "%10d%12s%12s%10.2f\n", record.account, record.lastName,
record.firstName, record.balance );

} // end while
} // end try
I/O Streaming
catch ( NoSuchElementException elementException )
{ System.err.println( "File improperly formed." );
input.close();
} // end catch 1
catch ( IllegalStateException stateException )
{
System.err.println( "Error reading from file." );
System.exit( 1 );
} // end catch 2
} // end method readRecords
I/O Streaming
public void closeFile() {// close file and terminate application
if ( input != null )
input.close(); // close file
} // end method closeFile
} // end class ReadingFromFile
public class TestIO {
public static void main(String[] args) {
ReadingFromFile read = new ReadingFromFile ();
read.openFile ();
read.readRecords ();
read.closeFile();
}}
I/O Streaming

The End

You might also like