Top Banner
Mar 25, 2 022 Sequential Files and Streams
24

5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

Dec 13, 2015

Download

Documents

Leslie Murphy
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

Apr 18, 2023

Sequential Files and Streams

Page 2: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

2

File Handling.

File Concept.

Page 3: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

3

Files!

Reading data from a source outside of the program space or writing data to a location outside of the program space.

Program

Disk Disk

InternetInternet

read

read write

write

Page 4: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

4

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.

Page 5: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

5

File Handling.

open the file

Repeated access either read or write.

close the file

Page 6: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

6

Opening a file.

All file handling classes are in the java.io package. This must be imported.

import java.io.*; .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.

monthlySalesFile Specify how we will use the file.

we might want to read, write or append.

Page 7: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

7

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

Page 8: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

8

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

FileWriterprintln()

Raw Bytesformattedtext

Disk

Internet

Page 9: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

9

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.

Page 10: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

10

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.

Page 11: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

11

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.

Page 12: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

12

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.

Page 13: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

13

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

Page 14: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

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

Page 15: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

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

Page 16: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

16

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.

Page 17: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

17

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.

Page 18: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

18

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.

Page 19: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

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

Page 20: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

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

Page 21: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

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

Page 22: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

22

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.

Page 23: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

23

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

Page 24: 5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.

24

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