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

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
File Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
Files and Streams CS 21a Chapter 11 of Horstmann.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown )
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Two Ways to Store Data in a File Text format Binary format.
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
I/O in Java Dennis Burford
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
For Friday Finish reading chapter 9 WebCT quiz 17.
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Introduction to programming in java
Strings and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Creating and Modifying Text part 2
Working with files.
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
File Input and Output.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

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 Internet read write

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.

5 File Handling. open the file Repeated access either read or write. close the file

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.

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

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 FileWriter println() Raw Bytes formatted text Disk Internet

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.

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.

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.

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(" Joe's Fantastic Celsius Converter. "); prn.println("Celsius\tFahrenheit"); for(double celsius = ; celsius <= 20.0 ; celsius += 1.0 ){ fahrenheit = celsius * 5/ ; 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.

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

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

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.

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.

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.

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

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.

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

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