File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

AP Computer Science. File Input with Scanner. Copyright 2010 by Pearson Education

Building Java Programs Chapter 6

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Building Java Programs

CS 112 Introduction to Programming

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Files. Reading data from files. File class. Compiler error with files. Checked exceptions. Exceptions. Readings:

CS244 Advanced Programming Applications

Building Java Programs

Reading Input from Text File

CIS 110: Introduction to Computer Programming

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Peer Instruction 1. Elementary Programming

Building Java Programs

When we reach the line "z = x / y" the program crashes with the message:

Java Input/Output. 11 April 2013 OSU CSE 1

Input-Output and Exception Handling

Building Java Programs

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

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

Excep&ons and file I/O

File I/O Array Basics For-each loop

CSE 142, Spring Chapters 6 and 7 Line-Based File Input, Arrays. reading: , 7.1

Object-Oriented Programming in Java

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

FILE I/O. CS302 Introduction to Programming University of Wisconsin Madison Lecture 27. By Matthew Bernstein

Program 12 - Spring 2018

CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp

Java Errors and Exceptions. Because Murphy s Law never fails

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Unit 10: exception handling and file I/O

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Chapter 4: Loops and Files

Chapter 11 Handling Exceptions and Events. Chapter Objectives

An exception is simply an error. Instead of saying an error occurred, we say that an.

CSE 143 Lecture 22. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

CSE 143 Lecture 21. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

COMP-202 Unit 9: Exceptions

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CSCI 1103: File I/O, Scanner, PrintWriter

First Java Program - Output to the Screen

Text User Interfaces. Keyboard IO plus

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Chapter 4: Loops and Files

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Computer Science is...

Assignment 17 Deadline: Oct pm COSC211 CRN15376 Session 14 (Oct. 29)

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Lecture 7. File Processing

CS 302: Introduction to Programming in Java. Lectures 17&18. It s insanely hot. People desperately need some snowflakes

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

CSPP : Introduction to Object-Oriented Programming

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

COMP102: 181. Menu. More while loops. Admin: Test. Peter Andreae

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS 211: Existing Classes in the Java Library

BBM 102 Introduction to Programming II Spring Exceptions

Name: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.

Object Oriented Programming Exception Handling

COMP Streams and File I/O. Yi Hong June 10, 2015

Full file at

DPCompSci.Java.1718.notebook April 29, 2018

Advanced Java Concept Unit 1. Mostly Review

CP122 CS I. Chapter 11: File I/O and Exceptions

CSCI 1103: File I/O, Scanner, PrintWriter

Simple Java Input/Output

Input from Files. Buffered Reader

File I/O and Exceptions

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CS 112 Introduction to Programming

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Chapter 4 Classes in the Java Class Libraries

Pace University. Fundamental Concepts of CS121 1

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

CN208 Introduction to Computer Programming

Java Coding 3. Over & over again!

School of Informatics, University of Edinburgh

CP122 CS I. Chapter 11: File I/O and Exceptions

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

AP Computer Science Unit 1. Writing Programs Using BlueJ

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". Input is received from the keyboard, mouse, files. output is sent to the console, monitor, files, The File class represents files as objects, and is defined in the java.io package. Creating a File object allows you to get information about a file (on the hard disk or optical drive). 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(); CS 160, Fall Semester 2014 2 File methods Scanner reminder Some methods in the File class: Method name canread() delete() exists() getname() length() Description returns whether file can be read removes file from disk whether this file exists on disk returns name of file returns number of characters in file renameto(filename) changes name of file CS 160, Fall Semester 2014 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);! CS 160, Fall Semester 2014 4 1

Scanner reminder Scanner for reading a file Common methods called on Scanner: q Read a line String str = scan.nextline();! q Read a string (separated by whitespace)!string str = scan.next( );! q Read an integer!int ival = scan.nextint( );! q 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); CS 160, Fall Semester 2014 5 CS 160, Fall Semester 2014 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: q In Directory: "names.dat" q In Subdirectory: "code/example.java" absolute path: The complete pathname to a file starting at the root directory /: q In Linux: "/users/cs160/programs/example.java" q 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")); q If our program is in ~/workspace/p4 q Scanner will look for ~/workspace/p4/data/input.txt CS 160, Fall Semester 2014 7 CS 160, Fall Semester 2014 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! CS 160, Fall Semester 2014 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. CS 160, Fall Semester 2014 10 Exceptions Checked exceptions exception: An object that represents a program error. q Programs with invalid logic will cause exceptions. q Examples: dividing by zero calling charat on a String with an out of range index trying to read a file that does not exist q We say that a logical error results in an exception being thrown. q It is also possible to catch (handle) an exception. checked exception: An error that must be handled by our program (otherwise it will not compile). q We must specify what our program will do to handle any potential file I/O failures. q 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) CS 160, Fall Semester 2014 11 CS 160, Fall Semester 2014 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: q "I hereby agree that this method might throw an exception, and I accept the consequences (crashing) if this happens. q General syntax: public static <type> <name>(<params>) throws <type> { q When doing file open, we throw IOException. public static void main(string[] args) throws IOException { CS 160, Fall Semester 2014 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); CS 160, Fall Semester 2014 14 Fixing the compiler error Using Scanner to read a file 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. 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: q 308.2\n\t14.9 7.4 2.8\n\n3.9 4.7\t-15.4\n\t2.8\n CS 160, Fall Semester 2014 15 CS 160, Fall Semester 2014 16 4

Consuming tokens First problem Each call to next/nextline/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. CS 160, Fall Semester 2014 17 CS 160, Fall Semester 2014 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? CS 160, Fall Semester 2014 19 CS 160, Fall Semester 2014 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. q 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 @#*($& CS 160, Fall Semester 2014 21 CS 160, Fall Semester 2014 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(); CS 160, Fall Semester 2014 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. CS 160, Fall Semester 2014 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++; CS 160, Fall Semester 2014 25 CS 160, Fall Semester 2014 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 q Consider the task of computing hours worked by each person q 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>); q 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 CS 160, Fall Semester 2014 27 CS 160, Fall Semester 2014 28 7

Tokenize an entire file Entire 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...> CS 160, Fall Semester 2014 29 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 CS 160, Fall Semester 2014 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: " + 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. CS 160, Fall Semester 2014 31 CS 160, Fall Semester 2014 32 8