write - Sheridan

Download Report

Transcript write - Sheridan

Sequential Files and Streams
1-Apr-16
File Handling.

File Concept.
2
Files!

Reading data from a source outside of the
program space or writing data to a location outside
of the program space.
Internet
Internet
read
write
Program
read
Disk
write
Disk
3
The Stream Concept.



You can think of files as a stream of bytes coming
into or being exported out of a program.
This approach makes file processing more
complicated.
Java allows you to hook other objects into the raw
bytes of the stream to make handling data easier.

eg. Allow the output of specially formatted text from
variables in a program … The PrintWriter class which
has the println() method.
4
File Handling.
open the file
Repeated access
either read or write.
close the file
5
Opening a file.

All file handling classes are in the java.io package. This
must be imported.


.We must be able to identify where the information is on the
system….the file name on disk.


“febSales.dat”
Associate the filename on disk with an easy to use
identifier in the program…a variable name.


import java.io.*;
monthlySalesFile
Specify how we will use the file.

we might want to read, write or append.
6
Opening for Text Output.

We want to open a file by the name of
“febSales.dat” so that we could write using a println
command.
create a FileWriter object with argument “febSales.dat”.
FileWriter salesFile = new FileWriter(“febSales.dat”);


FileWriters write raw bytes. We want to use println.
println() is available in the PrintWriter class. Now we
create a PrintWriter object with our FileWriter as an
argument.
PrintWriter rptPrinter = new PrintWriter(salesFile);
7
File Handling- An OO Approach

Java uses a lego-block approach to file handling.
Real access to a file is as raw bytes using
FileWriters and FileReaders but lego-blocks
(also known as decorators) can be attached to
the Writers and Readers for convenience.
PrintWriter
println()
formatted
text
FileWriter
Raw Bytes
Disk
Internet
8
Problems…Problems.

File handling must reference outside data.Many
problems can occur here:





we typed in the wrong file name.
File name is right but someone has deleted it.
File name is right but we don’t have privileges to either
read or write the data.
many, many other problems.
Because of these problems we must wrap our file
handling code in a try catch. For now we will catch
the IOException exception.
9
Writing to files.

Several approaches to writing to files.





write formatted information to file similar to println()
output.
write a line at a time.
write a character at a time.
write a fixed block size of characters at a time.
Different file types.


text
binary.
10
Writing an Employee Data File



create a FileWriter specifying file name.
create a PrintWriter from the FileWriter.
loop until user quits.





prompt and get data for one employee.
write data for one employee to file.
endloop
close file.
end program.
11
import java.io.*;
public class DemoFileWrite {
public static void main(String[] args) {
try{
FileWriter outFile = new FileWriter("c2f.dat");
PrintWriter prn = new PrintWriter(outFile);
double fahrenheit;
prn.println("<H1>Joe's Fantastic Celsius Converter.<H1>");
prn.println("Celsius\tFahrenheit");
for(double celsius = -10.0 ; celsius <= 20.0 ; celsius += 1.0 ){
fahrenheit = celsius * 5/9.0 + 32.0;
prn.println(celsius + "\t" + fahrenheit + "\n");
}
prn.close();
} catch ( IOException ioe ){
System.out.println("Problem creating c2f.dat");
}
}
}
Store a table of Celsius Conversions to a File.
12
Writing an Employee Data File.
//…imports, and declarations for vars here.
try{
FileWriter outfile = new FileWriter("D:\\employees.dat");
PrintWriter prn = new PrintWriter( outfile);
System.out.println("Enter your name (QUIT will quit):");
name = keyboard.next();
while( !name.equals("QUIT")){
System.out.println("Enter your age:");
age = keyboard.nextInt();
prn.println(name + "," + age );
System.out.println("Enter your name (QUIT will quit):");
name = keyboard.next();
}
prn.close();
} catch (IOException ioe ){
System.out.println("Problem creating employees.dat");
}
13
Your Turn : Store a Times Table.

Write a Java program which will store into a file the
9 times table. Name the file ninetimes.dat. Your
format for each line should be “9 times 1 is 9”.
Provide a heading for the table. After running the
program load the file into notepad or some other
editor to view the results. You might need to do a
search to find it (it will be found in the same
directory where your program ran). For an
enhancement change the file so that it uses a
nested for loop to print out all times tables.
14
Questions.



Can a PrintWriter be constructed simply from a file
name or does it need to be constructed from some
other IO object?
Must IO tasks be enclosed in a try..catch or in
methods that throw an IOException?
Are there situations where writing to a file might
not work even if all the code was written correctly?
15
Reading from files.

Several approaches to reading from files.






read formatted information to file similar to scanner
input.
read a line at a time.
read a character at a time.
read a token at a time.
read a fixed block size of characters at a time.
Different file types.


text
binary.
16
The EOF Problem.



With every read of a sequential file (whether a
character, block, or line) there is the possibility that
we have reached the end-of-file (know as EOF).
file processing loops typically use the EOF
condition to terminate processing of the loop.
how you detect EOF depends on your file handling
approach and what method you use to read data.
17
Reading Files



create a BufferedReader out of a
FileReader.
to read a line at a timeuse the readLine()
method of the BufferedReader class.
If readLine() encounters an EOF it will
return a null string instead of a valid
string. We can use this to control our
loop.
18
Display File Contents:Line at a Time.
import java.io.*;
public class DisplayFile {
public static void main(String[] s) throws IOException {
BufferedReader in= null;
try {
in = new BufferedReader(new FileReader("D:\\c2f.dat"));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line); }
} finally {
if (in!= null)
{ in.close();}
}
}
}
Copy File Contents:Line at a Time.
import java.io.*;
public static void copyLines() throws IOException
{
BufferedReader in= null;
PrintWriter out = null;
try {
in = new BufferedReader(new FileReader("xanadu.txt"));
out = new PrintWriter(new FileWriter("characteroutput.txt"));
String line;
while ((line = in.readLine()) != null) {
out.println(line); }
} finally {
if (in!= null)
{ in.close(); }
if (out != null)
{ out.close(); }
}
}
Your Turn: Read and Display.

Your instructor should have provided you with a
file of information on Canadian provinces and
territories, provinces.dat. Write a program which
reads in the information in this file and displays it
to the screen.
21
Scanning Files for Tokens

The Scanner class simplifies reading numeric data
because you read and convert tokens with one
method.




nextInt() … reads next token and converts to int.
nextDouble() … reads next tokens and converts to
double.
next() … read next token as a String.
Subject to parse errors.
22
Reading a Data File:Token by Token.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;
public class DemoFileScanner {
public static void main(String[] args) throws IOException {
Scanner s = null;
double sum = 0, age = 0;
int count =0;
try {
……OPEN AND SCAN FILE HERE
} finally {
s.close(); // CLOSE FILE
}
System.out.println("Average age of employees is " + sum/count);
}
}
23
File Scanning.
try {
s = new Scanner(
new BufferedReader(new FileReader("D:\\employees1.dat")));
while (s.hasNext()) {
if( s.hasNext()){
System.out.print(s.next());
}
if (s.hasNextDouble()) {
age = s.nextDouble();
sum += age;
count++;
System.out.print(" " + age + "\n");
}
}
} finally {
s.close();
}
24