1 File Input. 2 Reading Files We have already seen that writing files is (can be?) similar to using System.out Not surprisingly, reading from files is.

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

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
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.
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
COMP 121 Week 5: Exceptions and Exception Handling.
More Java Syntax. Scanner class Revisited The Scanner class is a class in java.util, which allows the user to read values of various types. There are.
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.
Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.
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 
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
Files and Streams CS 21a Chapter 11 of Horstmann.
Lecture 3 Java Basics Lecture3.ppt.
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
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.
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.
Program 6 Any questions?. System.in Does the opposite of System.out.
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.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Chapter 12 Using data files. The concept of file Logically cohesive data stored on a permanent storage, such as hard disk (most cases), CD, USB. Types.
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.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
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.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
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.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Streams & File Input/Output (I/O)
Introduction to programming in java
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
I/O Basics.
CSS 161: Fundamentals of Computing
Unit 6 Working with files. Unit 6 Working with files.
Fundamental Error Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
File Input and Output.
ECE 122 April 14, 2005.
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:

1 File Input

2 Reading Files We have already seen that writing files is (can be?) similar to using System.out Not surprisingly, reading from files is similar to using System.in  …with a few extra wrinkles Again, the classes needed to do this are in java.io

3 The Reader Class The Reader class is used to read text  i.e. any stream of characters  it’s abstract: the parent of many subclasses  the counterpart of Writer Provides the read() method  reads single characters or character arrays  reads as many characters as it can, up to the array size

4 Reading Files The FileReader class is analogous to FileWriter  a subclass of Reader that can work on a file  constructor takes a filename as an argument Example Reader in = new FileReader(“somefile.txt”);

5 Example This reads and prints the first line of a file Reader filein = new FileReader(“file.txt”); char ch; do { ch = (char) filein.read(); System.out.print(ch); } while (ch!=‘\n’); filein.close() Create Reader object by giving filename. We will read character-by-character. Reading a character actually returns an int. Go until we find a new line. Should be closed when finished.

6 End of File When reading from System.in, we just waited for the user to type more When reading from a file, there might not be any more file to read  Our programs will have to handle the possibility that we’ve reached the end of the file  Different Reader methods have different ways of signaling the end of file

7 End of File in a Reader. read(): returns an integer, not a character. Returns -1 if end of file. Can cast to a character otherwise..read(char[]): puts characters into the array, returns the number of characters read; -1 if end of file.  so not all of the array will have meaningful contents, only characters 0 to return value;

8 Working with Reader Makes working with Reader tricky: Reader filein = new FileReader(“test.txt”); char[] buf = new char[10]; int numChars; while(true) { numChars = filein.read(buf); if(numChars==-1) break; System.out.print(“(“ + new String(buf, 0, numChars) + “)”); } Read into a character array Read as much as possible EOF when it returns -1; exit loop Convert characters 0…numChars to a String

9 Buffered Reading Many small reads are also innefficient The operating system typically reads ahead in the file and stores the next parts in memory  “disk cache” The BufferedReader class enhances this  Read the next part of the file into memory and just returns it when we try to read more  Speedup similar to BufferedWriter : a few times

10 BufferedReader Wraps an existing Reader object: Reader filein = new BufferedReader(new FileReader(“file.txt”)); Otherwise, it works just like any other Reader object  …but faster

11 Scanner We have already used a Scanner object to wrap the System.in stream Scanner userin = new Scanner(System.in); System.in is (almost) a Reader object  We can treat any other Reader object the same way

12 Example Read (and sum) integers in a file Reader filein = new BufferedReader( new FileReader(“numbers.txt”)); Scanner scanfile = new Scanner(filein); int total = 0; while(scanfile.hasNextInt()) { total += scanfile.nextInt(); } System.out.println(total); Construct Scanner with a Reader Knows how to check for more input … and convert appropriately

13 Incorrect Input When reading, the input might not be in the form you expect If you use plain Reader, you have to process the characters yourself  whatever logic does this should carefully check input to make sure it’s in the right form  it should only be accepted if it’s in the right form  if not, the program should fail gracefully

14 Bad Input and Scanner Calling nextWhatever() on a Scanner object throws an exception if it can’t read the appropriate type There are different reasons this could happen.  End of file ( NoSuchElementException )  Data input doesn’t look like the corresponding type ( InputMismatchException ) e.g. “abcd” having called nextInt()

15 Bad Input and Scanner The hasNextWhatever() methods will tell you (without an exception) if nextWhatever() will succeed  could be false because of end of file or bad input  be careful that’s really what you want to check e.g. previous example will stop as soon as there are any non-integers in the file

16 Dealing with Bad Input For keyboard input, you can ask the user to re-enter the value When reading a file, that isn’t possible  you should always consider what the “right” thing to do is  fail completely? Read data up to that point? Skip to the next line? Skip to next character? Ask the user? Can be very difficult, depending on the data

17 Example Read and sum integers, but handle errors  on bad input, throw away rest of line and try again We will also catch other checked exceptions  main() will no longer have to have a throws clause

18 Example, Part 1 Open file, init variables, catch exceptions Reader filein; try{ filein = new FileReader(“numbers.txt”); } catch(FileNotFoundException e){ System.out.println(“Couldn’t open the file.”); return; // exit main and stop program } Scanner scanfile = new Scanner(filein); int total = 0; boolean done = false;

19 Example, Part 2 while(!done) { try{ total += scanfile.nextInt(); } catch(InputMismatchException e){ //not an integer: eat rest of line scanfile.nextLine(); } catch(NoSuchElementException e){ //end of file done = true; } System.out.println(total);