Building Java Programs

Slides:



Advertisements
Similar presentations
CIS 1068 Program Design and Abstraction
Advertisements

Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
1 CSE 142 Lecture Notes File input using Scanner Suggested reading: , Suggested self-checks: Section 6.7 # 1-11, These lecture.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
CS305j Introduction to Computing File Processing 1 Topic 18 File Processing " We have also obtained a glimpse of another crucial idea about languages and.
Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
Topic 19 file input, line based Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
1 BUILDING JAVA PROGRAMS CHAPTER 6 DETAILS OF TOKEN-BASED PROCESSING.
BUILDING JAVA PROGRAMS CHAPTER 6 File Processing.
Topic 18 file input, tokens Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
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.
Building Java Programs File Processing. 2 Input/output (I/O) import java.io.*; Create a File object to get info about a file on your drive. –(This doesn't.
FILE PROCESSING. Reading files To read a file, pass a File when constructing a Scanner. Scanner name = new Scanner(new File(" file name ")); Example:
Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
Building Java Programs
Building Java Programs
File - CIS 1068 Program Design and Abstraction
Building Java Programs Chapter 6
CMSC 202 Text File I/O.
Introduction to programming in java
CSc 110, Autumn 2017 Lecture 19: While loops and File Input
Lecture 3: Input/Output
Building Java Programs
File Input and Output TOPICS File Input Exception Handling File Output.
Building Java Programs
CSc 110, Autumn 2017 Lecture 18: While loops and File Input
File Input and Output TOPICS File Input Exception Handling File Output.
Building Java Programs
Building Java Programs
Building Java Programs Chapter 6
Building Java Programs Chapter 6
Building Java Programs
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Topic 18 file input, tokens
Building Java Programs
Building Java Programs
Input/output (I/O) import java.io.*;
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Files Readings: 6.1 – 6.2.
Building Java Programs
Building Java Programs
Topic 19 file input, line based
Input/output (I/O) import java.io.*;
Building Java Programs
CIS 110: Introduction to Computer Programming
Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4
Building Java Programs
Presentation transcript:

Building Java Programs Chapter 6: File Processing These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2006. They may not be rehosted, sold, or modified without expressed permission from the authors. All rights reserved.

Chapter outline Basic file reading using Scanner File objects throwing exceptions file names and folder paths Line-by-line processing processing a file line by line examining the contents of an individual line searching for a particular line in a file handling complex and multi-line input records handling the file-not-found case Basic file writing using PrintStream

File reading using Scanner suggested reading: 6.1 - 6.2

File objects Java's File class (in the java.io package) represents files on the user's hard drive. Remember to import java.io.*; When we want to read data out of a file, we create a File object representing that file and open it with a Scanner. Creating a File object does not actually create that file on your hard drive. The file should already exist if you want to read it. Creating a Scanner for a file, general syntax: Scanner <name> = new Scanner(new File("<file name>")); Example: Scanner input = new Scanner(new File("numbers.txt"));

File and path names relative path: does not specify any top-level folder "names.dat" "input/kinglear.txt" absolute path: specifies drive letter or top "/" folder "C:/Documents/smith/hw6/input/data.csv" Windows systems also use backslashes to separate folders. How would the above filename be written using backslashes? In DrJava, TextPad, and most other editors, when you construct a File object with a relative path, Java assumes it is relative to the the current directory. Scanner input = new Scanner(new File("data/readme.txt")); If our program is in the folder H:/johnson/hw6, Java will look for H:/johnson/hw6/data/readme.txt.

Compiler error with files The following program does not compile: import java.io.*; // for File import java.util.*; // for Scanner public class ReadFile { public static void main(String[] args) { Scanner input = new Scanner(new File("data.txt")); String text = input.next(); System.out.println(text); } The following compiler error is produced: ReadFile.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown ^

Exceptions exception: An object that represents a program error. Programs that contain invalid logic, such as dividing by zero, cause ("throw") exceptions. Trying to read a file that does not exist will also throw an exception. checked exception: An error that Java forces us to handle in our program; otherwise the program will not compile. Java forces us to specify what our program should do to handle potential failures when opening a file. We must either declare that our program will handle ("catch") the exception to repair it, or we must explicitly say that we choose not to handle the exception (and we choose to take the risk of our program crashing if the exception occurs).

Throwing exception syntax throws clause: Keywords that can be added to the header of our methods to explain to Java that we plan NOT to handle file input failures. The program will crash in such a case. Throws clause, general syntax: public static <type> <name>(<params>) throws <type> { The checked exception that Java requires us to handle when doing file I/O is called a FileNotFoundException. public static void main(String[] args) throws FileNotFoundException {

Fixed compiler error The following corrected version of the program does compile: import java.io.*; // for File, FileNotFoundException import java.util.*; // for Scanner public class ReadFile { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("data.txt")); String text = input.next(); System.out.println(text); }

Files and input cursor Consider a file named numbers.dat 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, which it processes with its input cursor: 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n ^ When you call the methods of the Scanner such as next or nextDouble, the Scanner breaks apart the input into tokens. token: A unit of user input. Tokens are separated by whitespace (spaces, tabs, new lines).

Reading tokens If an input file contains the following: 23 3.14 "John Smith" The tokens in the input are the following, and can be interpreted as the given types: Token Type(s) 1. 23 int, double, String 2. 3.14 double, String 3. "John String 4. Smith" String Each call to next, nextInt, nextDouble, etc. advances the cursor to the end of the current token, skipping over any whitespace. input.nextDouble() 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n ^

File input question Consider an input file named numbers.dat that contains the following text: 308.2 14.9 7.4 2.8 3.9 4.7 -15.4 2.8 Write a program that reads the first 5 values from this file and prints them along with their sum. Its output: number = 308.2 number = 14.9 number = 7.4 number = 2.8 number = 3.9 Sum = 337.19999999999993

File input answer import java.io.*; // for File, FileNotFoundException // Displays several numbers in the given file, // and displays their sum at the end. public class Echo { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("numbers.dat")); double sum = 0.0; for (int i = 1; i <= 5; i++) { double next = input.nextDouble(); System.out.println("number = " + next); sum += next; } System.out.println("Sum = " + sum); Input File numbers.dat: Output: 308.2 number = 308.2 14.9 7.4 2.8 number = 14.9 number = 7.4 3.9 4.7 -15.4 number = 2.8 2.8 number = 3.9 Sum = 337.19999999999993

Testing before reading The preceding program is impractical because it only processes exactly 5 values from the input file. A better program would be general and read the entire file regardless of how many values it contains. Reminder: The Scanner has useful methods for testing to see what the next input token will be: You can call these methods as the test of an if statement or loop. Method Name Description hasNext() whether any more tokens remain hasNextDouble() whether the next token can be interpreted as type double hasNextInt() whether the next token can be interpreted as type int hasNextLine() whether any more lines remain

Test before read question Rewrite the previous program so that it reads until the end of the file. Its output: number = 308.2 number = 14.9 number = 7.4 number = 2.8 number = 3.9 number = 4.7 number = -15.4 Sum = 329.29999999999995

Test before read answer import java.io.*; // Displays each number in the given file, // and displays their sum at the end. public class Echo2 { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("numbers.dat")); double sum = 0.0; while (input.hasNextDouble()) { double next = input.nextDouble(); System.out.println("number = " + next); sum += next; } System.out.println("Sum = " + sum); Input File numbers.dat: Output: 308.2 number = 308.2 14.9 7.4 2.8 number = 14.9 number = 7.4 3.9 4.7 -15.4 number = 2.8 2.8 number = 3.9 number = 4.7 number = -15.4 number = 2.8 Sum = 329.29999999999995

File processing problem Write a program that reads a file of integers and prints their average. For added challenge, make your program able to skip over any non-integer tokens in the file and ignore them. Example input file: 1 TEST 2 3 4 5 3.7 6 many bad tokens 7 27.5 8 9 Hello 10 Output: Average = 5.5

File processing problem Write a program that accepts an input file containing integers representing daily high temperatures. Example input file: 42 45 37 49 38 50 46 48 48 30 45 42 45 40 48 Your program should print the difference between each adjacent pair of temperatures, such as the following: Temperature changed by 3 deg F Temperature changed by -8 deg F Temperature changed by 12 deg F Temperature changed by -11 deg F Temperature changed by -4 deg F Temperature changed by 2 deg F Temperature changed by 0 deg F Temperature changed by -18 deg F Temperature changed by 15 deg F Temperature changed by -3 deg F Temperature changed by -5 deg F Temperature changed by 8 deg F