Reading a Text File. Reading and Writing Text Files Exceptions. Testing for more input. Example: Count Words

Similar documents
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Using Files as Input/Output in Java 5.0 Applications

CS 111 Classes I 1. Software Organization View to this point:

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

What are exceptions? Bad things happen occasionally

Object-Oriented Programming in Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

AP Computer Science File Input with Scanner

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

D06 PROGRAMMING with JAVA

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Introduction to Java

JAVA.UTIL.SCANNER CLASS

Reading Input From A File

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Simple Java I/O. Streams

Visit us at

Course Intro Instructor Intro Java Intro, Continued

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

13 File Output and Input

Basics of Java Programming Input and the Scanner class

Lecture J - Exceptions

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Introduction to Programming

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Homework/Program #5 Solutions

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Building Java Programs

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

AP Computer Science Java Subset

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Event-Driven Programming

Building Java Programs

Files and input/output streams

Topic 11 Scanner object, conditional execution

Install Java Development Kit (JDK) 1.8

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Software Construction

Chapter 2: Elements of Java

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Fundamentals of Java Programming

Explain the relationship between a class and an object. Which is general and which is specific?

AP Computer Science Java Mr. Clausen Program 9A, 9B

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS506 Web Design and Development Solved Online Quiz No. 01

Stream Classes and File I/O

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

CS 1302 Ch 19, Binary I/O

AP Computer Science Static Methods, Strings, User Input

public static void main(string[] args) { System.out.println("hello, world"); } }

D06 PROGRAMMING with JAVA

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

WRITING DATA TO A BINARY FILE

Java Application Developer Certificate Program Competencies

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Comp 248 Introduction to Programming

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Building Java Programs

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Building a Multi-Threaded Web Server

Chapter 2 Introduction to Java programming

Week 1: Review of Java Programming Basics

CSE 1020 Introduction to Computer Science I A sample nal exam

CS 106 Introduction to Computer Science I

Creating a Simple, Multithreaded Chat System with Java

Sample CSE8A midterm Multiple Choice (circle one)

Using Two-Dimensional Arrays

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

6.1. Example: A Tip Calculator 6-1

Crash Course in Java

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Division of Informatics, University of Edinburgh

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Lecture 5: Java Fundamentals III

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Chapter 3. Input and output. 3.1 The System class

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Quick Introduction to Java

CSE 8B Midterm Fall 2015

Introduction to Java. CS 3: Computer Programming in Java

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

OBJECT ORIENTED PROGRAMMING LANGUAGE

core 2 Basic Java Syntax

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Software Development in Java

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Line-based file processing

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Software Engineering Techniques

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Transcription:

Reading a Text File Reading and Writing Text Files Exceptions 15-121 Fall 2010 Margaret Reid-Miller A Scanner object can be connected to many input sources: keyboard, file, network, string To read a text file, we create a Scanner object passing a File object instead of System.in as the argument: creates a Java File // Read from data.txt file! object (does not create Scanner infile =! a file on your disk)!!new Scanner(new File( data.txt ));! int numvalues = infile.nextint(); Fall 2010 15-121 (Reid-Miller) 2 Testing for more input Scanner has methods to check for more input: boolean hasnextline()! Return true if the scanner object has another line in its input. boolean hasnext()! Return true if the scanner object has any more tokens in its input. boolean hasnextint()! Return true if the scanner object has another token in its input and that token can be read as an int. boolean hasnextdouble()! Return true if the scanner object has another token in its input and that token can be read as a double. These methods do not consume input; They just say whether and what kind of input is waiting. Fall 2010 15-121 (Reid-Miller) 3 Example: Count Words public static void main(string[] args)!!!!! throws IOException {!!!Scanner infile = new Scanner!!!!!!!(new File( essay.txt ));! int count = 0;!!while (infile.hasnext()) {!!!String word = infile.next();!!!count++;!!!system.out.println( Number of words is!!!!!!+ count);! Fall 2010 15-121 (Reid-Miller) 4

Exceptions Exceptions are unusual or erroneous situations from which a program may be able to recover. Often the problem is out of the control of the program, such as bad user input. When a exception occurs the Java runtime system creates an Exception object that holds information about the problem. An exception will cause a program to halt unless it is caught and handled with special code. Errors Errors are problems that are so severe that it is not possible to recover from them, e.g., hardware error. Errors are objects of the class Error. Example: OutOfMemoryError Programs can recover from Exceptions but must stop running for Errors. Object Throwable Exception Error Fall 2010 15-121 (Reid-Miller) 5 Fall 2010 15-121 (Reid-Miller) 6 Two Types of Exceptions Common Exceptions with Files Checked (compile-time) - Generally indicates invalid conditions outside of the program. The compiler requires that you handle these exceptions explicitly. Examples: IOException! FileNotFoundException Unchecked (runtime)- Generally indicates error in the program s logic. Examples: ArrayIndexOutOfBoundsException! NullPointerException Any exception that inherits from RuntimeException is unchecked, otherwise it is checked. Fall 2010 15-121 (Reid-Miller) 7 FileNotFoundException: (compile-time)!could not find the file: The file should be in the folder from which you invoke the program. NoSuchElementException: (runtime)!attempted to read passed the end of the file. (E.g., A loop reads 8 integers when there are only 7 integers.) InputMismatchException: (runtime)!attempted to read one type of token, but the next token was a different type. (E.g., Used nextint when the next token contained letters.) Fall 2010 15-121 (Reid-Miller) 8

Handling Exceptions When an exception occurs a method can either catch the exception and execute some code to handle it, or throw the exception back to the method that called this method so that it may handle the exception. If the exception is a (compile-time) checked exception, the method must declare that it throws the exception. Fall 2010 15-121 (Reid-Miller) 9 Throwing an Exception Explicitly import java.util.scanner;! import java.io.*; // for File! public class DataAnalyzer {!!public static void main(string[] args)!!!! throws FileNotFoundException {!!!Scanner fileinput = new Scanner(!!! new File( data.txt ));! If there is a problem with opening the file for reading, Scanner will throw an exception. If Scanner throws an exception, then main will throw it also (instead of catching it). Fall 2010 15-121 (Reid-Miller) 10 Example A robust program handles bad input gracefully, such as asking the user to reenter the name of a file when the file is not found. Scanner console = new Scanner(System.in);! System.out.print( Enter file name: )! String filename = console.nextline(filename);! Scanner filein = new Scanner(! new File(fileName));! If the user mistypes the file name, Scanner throws a FileNotFoundExcpetion. Fall 2010 15-121 (Reid-Miller) 11 Catching the Exception String filename = null;! do {!!System.out.print( Enter file name: )! String filename = console.nextline(filename);! try {! Scanner in = new Scanner(new File(fileName));! ex is a reference to the catch (FileNotFoundException ex) { exception object. System.out.println( Error: File not found ); filename = null; while (filename == null); The catch block can call methods on ex to find out more details about the exception. Fall 2010 15-121 (Reid-Miller) 12

Using a try-catch Statement Flow of Control Put code that might throw an exception in a try block. Put code that handles the exception in a catch block immediately following the try block. When the code inside the try block is executed: If there are no exceptions, execution skips the catch block and continues after the catch block. If there is an exception, execution goes immediately to the catch block and then continues after the catch block. no exception try {! exception thrown catch(){! (take first match) catch(){! (no match) throw to caller Fall 2010 15-121 (Reid-Miller) 13 Fall 2010 15-121 (Reid-Miller) 14 Writing a Text File Writing to a text file is similar to writing to System.out (console):! public static void main(string[] args)!!!!!!throws IOException {!! name of file PrintWriter outfile = new PrintWriter(! to create!!!!! results.txt );! outfile.println( ANALYSIS for + infilename);! outfile.print( Number of samples );!! outfile.close(); Class requires import java.io.*;! Must close output file to ensure all the data are written to the file before the program terminates. Fall 2010 15-121 (Reid-Miller) 15 Exception Hierarchy By looking at the Java API, you can determine whether an exception inherits from the RuntimeException class. If not, the method must catch or specify it throws the exception. Exception! RuntimeException! IOException! (unchecked) (checked) FileNotFoundException! NoSuchElementException! ArithmeticException! InputMismatchException! Fall 2010 15-121 (Reid-Miller) 16

Using throws vs try-catch Methods can either catch or throw exceptions that occur during its execution. If the method throws it to its caller, the caller similarly can either catch or throw the exception. If the exception gets thrown all the way back to the main method and the main method also throws it, the runtime system stops the program and prints the exception with a call stack trace. Deciding which method should handle an exception is a software design decision, as is defining new exceptions for special types of errors. Fall 2010 15-121 (Reid-Miller) 17