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



Similar documents
AP Computer Science File Input with Scanner

Object-Oriented Programming in Java

13 File Output and Input

Reading Input From A File

Line-based file processing

CS 121 Intro to Programming:Java - Lecture 11 Announcements

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

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

Building Java Programs

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

Using Files as Input/Output in Java 5.0 Applications

Building Java Programs

Topic 11 Scanner object, conditional execution

Basics of Java Programming Input and the Scanner class

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

Chapter 2: Elements of Java

Introduction to Java

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

Introduction to Java. CS 3: Computer Programming in Java

Install Java Development Kit (JDK) 1.8

Building Java Programs

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

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

Course Intro Instructor Intro Java Intro, Continued

CS506 Web Design and Development Solved Online Quiz No. 01

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

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

D06 PROGRAMMING with JAVA

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

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

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

Chapter 2 Introduction to Java programming

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

Programming Languages CIS 443

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

J a v a Quiz (Unit 3, Test 0 Practice)

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

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

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

Chapter 3. Input and output. 3.1 The System class

CS 1302 Ch 19, Binary I/O

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

C++ INTERVIEW QUESTIONS

Token vs Line Based Processing

Lecture 5: Java Fundamentals III

Lecture J - Exceptions

Chapter 2 Basics of Scanning and Conventional Programming in Java

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

Event-Driven Programming

WRITING DATA TO A BINARY FILE

Files and input/output streams

Visit us at

Introduction to Programming

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

CS 106 Introduction to Computer Science I

Week 1: Review of Java Programming Basics

Part I. Multiple Choice Questions (2 points each):

6.1. Example: A Tip Calculator 6-1

Java Programming Fundamentals

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

Moving from CS 61A Scheme to CS 61B Java

CS170 Lab 11 Abstract Data Types & Objects

Sample CSE8A midterm Multiple Choice (circle one)

Assignment 4 Solutions

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

LAB4 Making Classes and Objects

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

Homework/Program #5 Solutions

Continuous Integration Part 2

(Eng. Hayam Reda Seireg) Sheet Java

Building Java Programs

JAVA.UTIL.SCANNER CLASS

D06 PROGRAMMING with JAVA

Creating a Simple, Multithreaded Chat System with Java

JAVA - FILES AND I/O

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

Comp 248 Introduction to Programming

Division of Informatics, University of Edinburgh

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

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Interactive Programs and Graphics in Java

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

AP Computer Science Java Subset

Programming and Data Structures with Java and JUnit. Rick Mercer

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

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

INPUT AND OUTPUT STREAMS

Programming Fundamentals I CS 110, Central Washington University. November 2015

java Features Version April 19, 2013 by Thorsten Kracht

Java from a C perspective. Plan

Introduction to Java Lecture Notes. Ryan Dougherty

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Fundamentals of Java Programming

Using Two-Dimensional Arrays

Introduction to Object-Oriented Programming

Transcription:

File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The class is defined in the java.io package. Creating a File object allows you to get information about a file on the disk. Creating a File object does NOT create a new file on your disk. File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); 10/16/12 CS 160, Fall Semester 2012 2 Files Scanner reminder Some methods in the File class: Method name canread() Description returns whether file can be read delete() removes file from disk exists() whether this file exists on disk getname() returns name of file length() returns number of characters in file renameto(filename) changes name of file 10/16/12 CS 160, Fall Semester 2012 3 The Scanner class reads input and processes strings and numbers from the user. When constructor is called with System.in, the character stream is input typed to the console. Instantiate Scanner by passing the input character stream to the constructor: Scanner scan = new Scanner(System.in); 10/16/12 CS 160, Fall Semester 2012 4 1

Scanner reminder Opening a file for reading Common methods called on Scanner: Read a line String str = scan.nextline(); Read a string (separated by whitespace) String str = scan.next( ); Read an integer int ival = scan.nextint( ); Read a double double dval = scan.nextdouble( ); To read a file, pass a File object as a parameter when constructing a Scanner String variable Scanner for a file: or string literal Scanner <name> = new Scanner(new File(<filename>)); Example: Scanner scan= new Scanner(new File("numbers.txt")); or: File file = new File("numbers.txt"); Scanner scan= new Scanner(file); 10/16/12 CS 160, Fall Semester 2012 5 10/16/12 CS 160, Fall Semester 2012 6 File names and paths File names and paths relative path: does not specify any top-level folder, so the path is relative to the current directory: "names.dat" "code/example.java" absolute path: The complete pathname to a file starting at the root directory /: In Linux: /users/cs160/programs/example.java In Windows: C:/Documents/cs160/programs/data.csv When you construct a File object with a relative path, Java assumes it is relative to the current directory. Scanner scan = new Scanner(new File( data/input.txt )); If our program is in ~/workspace/p4 Scanner will look for ~/workspace/p4/data/input.txt 10/16/12 CS 160, Fall Semester 2012 7 10/16/12 CS 160, Fall Semester 2012 8 2

Compiler error with files Compiler error with files Question: Why will the following program NOT compile? import java.io.*; import java.util.*; // for File // for Scanner public class ReadFile { public static void main(string[] args) { File file = new File( input.txt ); Scanner scan = new Scanner(file); String text = scan.next(); System.out.println(text); Answer: Because of Java exception handling! 10/16/12 CS 160, Fall Semester 2012 9 Here is the compilation error that is produced: ReadFile.java:6: unreported exception java.io.filenotfoundexception; must be caught or declared to be thrown Scanner scan = new Scanner(new File("data.txt")); The problem has to do with error reporting. What to do when a file cannot be opened? File may not exist, or may be protected. Options: exit program, return error, or throw exception Exceptions are the normal error mechanism in Java. 10/16/12 CS 160, Fall Semester 2012 10 Exceptions exception: An object that represents a program error. Programs with invalid logic will cause exceptions. Examples: dividing by zero calling charat on a String with an out of range index trying to read a file that does not exist We say that a logical error results in an exception being thrown. It is also possible to catch (handle) an exception. Checked exceptions checked exception: An error that must be handled by our program (otherwise it will not compile). We must specify what our program will do to handle any potential file I/O failures. We must either: declare that our program will handle ("catch") the exception, or state that we choose not to handle the exception (and we accept that the program will crash if an exception occurs) 10/16/12 CS 160, Fall Semester 2012 11 10/16/12 CS 160, Fall Semester 2012 12 3

Throwing Exceptions Handling Exceptions throws clause: Keywords placed on a method's header to state that it may generate an exception. It's like a waiver of liability: "I hereby agree that this method might throw an exception, and I accept the consequences (crashing) if this happens. General syntax: public static <type> <name>(<params>) throws <type> { When doing file open, we throw IOException. public static void main(string[] args) throws IOException { 10/16/12 CS 160, Fall Semester 2012 13 When doing file I/O, we use IOException. public static void main(string[] args) { try { File file = new File( input.txt); Scanner scan = new Scanner(file); String firstline = scan.nextline();... catch (IOException e) { System.out.println( Unable to open input.txt ); System.exit(-1); 10/16/12 CS 160, Fall Semester 2012 14 Fixing the compiler error Throwing an exception or handling the exception both resolve the compiler error. Throwing Exceptions: User will see program terminate with exception, that s not very friendly. Handling Exceptions: User gets a clear indication of problem with error message, that s much better. We will handle exceptions when reading and writing files in programming assignments. Using Scanner to read file data Consider a file numbers.txt that contains this text: 308.2 14.9 7.4 2.8 3.9 4.7-15.4 2.8 A Scanner views all input as a stream of characters: 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7-15.4\n2.8\n 10/16/12 CS 160, Fall Semester 2012 15 10/16/12 CS 160, Fall Semester 2012 16 4

Consuming tokens First problem Each call to next, nextint, nextdouble, etc. advances the position of the scanner to the end of the current token, skipping over any whitespace: 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7-15.4\n2.8\n scan.nextdouble(); 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7-15.4\n2.8\n scan.nextdouble(); 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7-15.4\n2.8\n Write code that reads the first 5 double values from a file and prints. 10/16/12 CS 160, Fall Semester 2012 17 10/16/12 CS 160, Fall Semester 2012 18 First solution Second problem public static void main(string[] args) try { File file = new File( input.txt ); Scanner scan = new Scanner(file); for (int i = 0; i <= 4; i++) { double next = scan.nextdouble(); System.out.println("number = " + next); catch (IOException e) { System.out.println( Unable to open input.txt ); System.exit(-1); How would we modify the program to read all the file? 10/16/12 CS 160, Fall Semester 2012 19 10/16/12 CS 160, Fall Semester 2012 20 5

Second solution Refining the problem public static void main(string[] args) try { File file = new File( input.txt ); Scanner scan = new Scanner(file); while (scan.hasnextdouble() { double next = scan.nextdouble(); System.out.println("number = " + next); catch (IOException e) { System.out.println( Unable to open input.txt ); System.exit(-1); Modify the program again to handle files that also contain non-numeric tokens. The program should skip any such tokens. For example, it should produce the same output as before when given this input file: 308.2 hello 14.9 7.4 bad stuff 2.8 3.9 4.7 oops -15.4 :-) 2.8 @#*($& 10/16/12 CS 160, Fall Semester 2012 21 10/16/12 CS 160, Fall Semester 2012 22 Refining the program Reading input line-by-line while (scan.hasnext()) { if (scan.hasnextdouble()) { double next = scan.nextdouble(); System.out.println("number = " + next); else { // consume the bad token scan.next(); 10/16/12 CS 160, Fall Semester 2012 23 Given the following input data: 23 3.14 John Smith "Hello world" 45.2 19 The Scanner can read it line-by-line: 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n scan.nextline() 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n scan.nextline() 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n The \n character is consumed but not returned. 10/16/12 CS 160, Fall Semester 2012 24 6

File processing question Solution Write a program that reads a text file and adds line numbers at the beginning of each line int count = 0; while (scan.hasnextline()) { String line = scan.nextline(); System.out.println(count + + line); count++; 10/16/12 CS 160, Fall Semester 2012 25 10/16/12 CS 160, Fall Semester 2012 26 Problem Scanner on strings Given a file with the following contents: 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jennifer 8.0 8.0 8.0 8.0 7.5 Consider the task of computing hours worked by each person Approach: Break the input into lines. Break each line into tokens. A Scanner can tokenize a String, such as a line of a file. Scanner <name> = new Scanner(<String>); Example: String text = "1.4 3.2 hello 9 27.5"; Scanner scan = new Scanner(text); System.out.println(scan.next()); // 1.4 System.out.println(scan.next()); // 3.2 System.out.println(scan.next()); // hello 10/16/12 CS 160, Fall Semester 2012 27 10/16/12 CS 160, Fall Semester 2012 28 7

Tokenize an entire file Example We can use string Scanner(s) to tokenize each line of a file: Scanner scan = new Scanner(new File(<file name)); while (scan.hasnextline()) { String line = scan.nextline(); Scanner linescan = new Scanner(line); <process this line...>; 10/16/12 CS 160, Fall Semester 2012 29 Example: Count the tokens on each line of a file. Scanner scan = new Scanner(new File("input.txt")); while (scan.hasnextline()) { String line = scan.nextline(); Scanner linescan = new Scanner(line); int count = 0; while (linescan.hasnext()) { String token = linescan.next(); count++; System.out.println("Line has +count+" tokens"); Input file input.txt: 23 3.14 John Smith "Hello world" 45.2 19 Output to console: Line has 6 tokens Line has 2 tokens 10/16/12 CS 160, Fall Semester 2012 30 Opening a file for writing File output Same story as reading, we must handle exceptions: public static void main(string[] args) { try { File file = new File( output.txt ); PrintWriter output = new PrintWriter(file); output.println( Integer number: + 987654);... catch (IOException e) { System.out.println( Unable to write output.txt ); System.exit(-1); You can output all the same things as you would with System.out.println: Discussion so far has been limited to text files. output.println( Double: " + fmt.format(123.456)); output.println("integer: " + 987654); output.println("string: " + "Hello There"); Binary files store data as numbers, not characters. Binary files are not human readable, but more efficient. 10/16/12 CS 160, Fall Semester 2012 31 10/16/12 CS 160, Fall Semester 2012 32 8