0% found this document useful (0 votes)
19 views34 pages

Chapter 6 Files and Streams

Uploaded by

firomsadine59
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)
19 views34 pages

Chapter 6 Files and Streams

Uploaded by

firomsadine59
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/ 34

Chapter 6

Files and
1 Streams
Objectives
Become familiar with the concept of an I/O
stream
Understand the difference between binary
files and text files
Learn how to save data in a file
Learn how to read data from a file
Outline
Overview of Streams and File I/O
Text-File I/O
Using the File Class
Basic Binary-File I/O
Object I/O with Object Streams
I/O Overview
 I/O = Input/Output
 In this context it is input to and output from programs
 Input can be from keyboard or a file
 Output can be to display (screen) or a file
 Advantages of file I/O
 permanent copy
 output from one program can be input to another
 input can be automated (rather than entered
manually)
Streams
 Stream: an object that either delivers data to its
destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
 it acts as a buffer between the data source and
destination
 Input stream: a stream that provides input to a
program
 System.in is an input stream
 Output stream: a stream that accepts output from a
program
 System.out is an output stream
 A stream connects a program to an I/O object
 System.out connects a program to the screen
 System.in connects a program to the keyboard
Binary Versus Text Files
 All data and programs are ultimately just zeros and ones
 each digit can have one of two values, hence binary
 bit is one binary digit
 byte is a group of eight bits
 Text files: the bits represent printable characters
 one byte per character for ASCII, the most common code
 for example, Java source files are text files
 so is any file created with a "text editor"
 Binary files: the bits represent other types of encoded
information, such as executable instructions or numeric data
 these files are easily read by the computer but not humans
 they are not "printable" files
 actually, you can print them, but they will be
unintelligible
 "printable" means "easily readable by humans when
printed"
Text File I/O
 Important classes for text file output (to the file)
 PrintWriter
 FileOutputStream [or FileWriter]
 Important classes for text file input (from the file):
 BufferedReader
 FileReader
 FileOutputStream and FileReader take file names as
arguments.
 PrintWriter and BufferedReader provide useful methods
for easier writing and reading.
 Usually need a combination of two classes
 To use these classes your program needs a line like the
following:
import java.io.*;
Buffering
 Not buffered: each byte is read/written from/to disk as
soon as possible
 “little” delay for each byte
 A disk operation per byte---higher overhead
 Buffered: reading/writing in “chunks”
 Some delay for some bytes
 Assume 16-byte buffers
 Reading: access the first 4 bytes, need to wait for all
16 bytes are read from disk to memory
 Writing: save the first 4 bytes, need to wait for all 16
bytes before writing from memory to disk
 A disk operation per a buffer of bytes---lower overhead
Every File Has Two Names
1.the stream name used by Java
 outputStream in the example

2.the name used by the


operating system
 out.txt in the example
Text File Output
 To open a text file for output: connect a text file to a stream
for writing
PrintWriter outputStream =
new PrintWriter(new FileOutputStream("out.txt"));

 Similar to the long way:


FileOutputStream s = new FileOutputStream("out.txt");
PrintWriter outputStream = new PrintWriter(s);

 Goal: create a PrintWriter object


 which uses FileOutputStream to open a text file
 FileOutputStream “connects” PrintWriter to a text file.
Output File Streams

PrintWriter FileOutputStream

Memory Disk

smileyOutStream smiley.txt

PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“smiley.txt”) );


Methods for PrintWriter
 Similar to methods for System.out
 println

outputStream.println(count + " " + line);

 print
 format
 flush: write buffered output to disk
 close: close the PrintWriter stream (and file)
TextFileOutputDemo
Part 1
A try-block is a block:
public static void main(String[] args) outputStream would
{ not be accessible to the
PrintWriter outputStream = null; rest of the method if it
try were declared inside the
{ Opening the file try-block
outputStream =
new PrintWriter(new
FileOutputStream("out.txt")); Creating a file can cause the
} FileNotFound-Exception if
catch(FileNotFoundException e) the new file cannot be made.
{
System.out.println("Error opening the file out.txt. “
+ e.getMessage());
System.exit(0);
}
TextFileOutputDemo
Part 2
System.out.println("Enter three lines of text:");
String line = null;
int count;
for (count = 1; count <= 3; count++)
{
line = keyboard.nextLine(); Writing to the file
outputStream.println(count + " " + line);
}
outputStream.close(); Closing the file
System.out.println("... written to out.txt.");
}
The println method is used with two different
streams: outputStream and System.out
Gotcha: Overwriting a File
 Opening an output file creates an empty file

 Opening an output file creates a new file if it does not


already exist

 Opening an output file that already exists eliminates the


old file and creates a new, empty one
 data in the original file is lost

 To see how to check for existence of a file, see the


section of the text that discusses the File class (later
slides).
Java Tip: Appending to a Text
File
 To add/append to a file instead of replacing it, use a different
constructor for FileOutputStream:
outputStream =
new PrintWriter(new FileOutputStream("out.txt", true));

 Second parameter: append to the end of the file if it exists?


 Sample code for letting user tell whether to replace or
append:
System.out.println("A for append or N for new file:");
char ans = keyboard.next().charAt(0);
boolean append = (ans == 'A' || ans == 'a'); true if user
outputStream = new PrintWriter( enters 'A'
new FileOutputStream("out.txt", append));
Closing a File
 An output file should be closed when you are
done writing to it (and an input file should be
closed when you are done reading from it).

 Use the close method of the class


PrintWriter (BufferedReader also has a
close method).

 For example, to close the file opened in the


previous example:
outputStream.close();
 If a program ends normally it will close any files
that are open.
FAQ: Why Bother to Close a
File?
If a program automatically closes files when it ends
normally, why close them with explicit calls to close?

Two reasons:
1. To make sure it is closed if a program ends abnormally
(it could get damaged if it is left open).

2. A file opened for writing must be closed before it can be


opened for reading.
 Although Java does have a class that opens a file for
both reading and writing, it is not used in this text.
Text File Input
 To open a text file for input: connect a text file to a stream for
reading
 Goal: a BufferedReader object,
 which uses FileReader to open a text file
 FileReader “connects” BufferedReader to the text file
 For example:
BufferedReader smileyInStream =
new BufferedReader(new FileReader(“smiley.txt"));
 Similarly, the long way:
FileReader s = new FileReader(“smiley.txt");
BufferedReader smileyInStream = new
BufferedReader(s);
Input File Streams

BufferedReader FileReader

Memory Disk

smileyInStream smiley.txt

BufferedReader smileyInStream = new BufferedReader( new FileReader(“smiley.txt”) );


Methods for
BufferedReader
readLine: read a line into a String
no methods to read numbers directly, so
read numbers as Strings and then convert
them (StringTokenizer later)
read: read a char at a time
close: close BufferedReader stream
Testing for End of File in a
Text File

 When readLine tries to read beyond the end of a text


file it returns the special value null
 so you can test for null to stop processing a text file

 read returns -1 when it tries to read beyond the end of a


text file
 the int value of all ordinary characters is nonnegative

 Neither of these two methods (read and readLine) will


throw an EOFException.
Example: Using Null to
Test for End-of-File in a Text
File
When using
readLine
test for null int count = 0;
String line = inputStream.readLine();
while (line != null)
{
count++;
outputStream.println(count + " " + line);
line = inputStream.readLine();
}

When using read test for -1


Using Path Names
 Path name—gives name of file and tells which directory
the file is in
 Relative path name—gives the path starting with the
directory that the program is in
 Typical UNIX path name:
/user/smith/home.work/java/FileClassDemo.java
 Typical Windows path name:
D:\Work\Java\Programs\FileClassDemo.java
 When a backslash is used in a quoted string it must be
written as two backslashes since backslash is the escape
character:
"D:\\Work\\Java\\Programs\\FileClassDemo.java"
 Java will accept path names in UNIX or Windows format,
regardless of which operating system it is actually
running on.
File Class [java.io]
 Acts like a wrapper class for file names
 A file name like "numbers.txt" has only String properties
 File has some very useful methods
 exists: tests if a file already exists
 canRead: tests if the OS will let you read a file
 canWrite: tests if the OS will let you write to a file
 delete: deletes the file, returns true if successful
 length: returns the number of bytes in the file
 getName: returns file name, excluding the preceding path
 getPath: returns the path name—the full name

File numFile = new File(“numbers.txt”);


if (numFile.exists())
System.out.println(numfile.length());
File Objects and Filenames
 FileInputStream and FileOutputStream have
constructors that take a File argument as well as
constructors that take a String argument

PrintWriter smileyOutStream = new PrintWriter(new


FileOutputStream(“smiley.txt”));

File smileyFile = new File(“smiley.txt”);


if (smileyFile.canWrite())
PrintWriter smileyOutStream = new
PrintWriter(new FileOutputStream(smileyFile));
Alternative with Scanner
Instead of BufferedReader with FileReader,
then StringTokenizer
Use Scanner with File:
Scanner inFile =
new Scanner(new File(“in.txt”));
Similar to Scanner with System.in:
Scanner keyboard =
new Scanner(System.in);
Reading in int’s
Scanner inFile = new Scanner(new File(“in.txt"));
int number;
while (inFile.hasInt())
{
number = inFile.nextInt();
// …
}
Reading in lines of characters
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
// …
}
BufferedReader vs Scanner
(parsing primitive types)
Scanner
nextInt(), nextFloat(), … for parsing types
BufferedReader
read(), readLine(), … none for parsing
types
needs StringTokenizer then wrapper class
methods like Integer.parseInt(token)
BufferedReader vs Scanner
(Checking End of File/Stream (EOF))
BufferedReader
readLine() returns null
read() returns -1
Scanner
nextLine() throws exception
needs hasNextLine() to check first
nextInt(), hasNextInt(), …
Suggestion
Use Scanner with File
new Scanner(new File(“in.txt”))
Use hasNext…() to check for EOF
while (inFile.hasNext…())
Use next…() to read
inFile.next…() the ‘dots’ can be Line,
Float,Int……
Simpler and you are familiar with methods for
Scanner
Suggestion cont…
File input
Scanner inFile =
new Scanner(new File(“in.txt”));
File output
PrintWriter outFile =
new PrintWriter(new File(“out.txt”));
outFile.print(), println(), format(),
flush(), close(), …
Basic Binary File I/O
Reading Assignment

You might also like