1 Line-based file processing suggested reading:6.3.

Slides:



Advertisements
Similar presentations
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
Advertisements

BUILDING JAVA PROGRAMS CHAPTER 6.4 FILE OUTPUT. 22 PrintStream : An object in the java.io package that lets you print output to a destination such as.
Copyright 2008 by Pearson Education Line-based file processing reading: 6.3 self-check: #7-11 exercises: #1-4, 8-11.
Files 1. 2 Storage Modern computers have many different kinds of storage components: - memory (aka RAM or DRAM) - disks (aka “hard disks” or “hard drives”)
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 7 Lecture 7-3: File Output; Reference Semantics reading: , 7.1, 4.3, 3.3 self-checks:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
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 7: Arrays.
1 Files Readings: 6.1 – Reading data from files Creating a Scanner for a file, general syntax: Scanner = new Scanner(new File(" ")); Example: Scanner.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
Topic 20 more file processing Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
1 Scanner objects. 2 Interactive programs We have written programs that print console output. It is also possible to read input from the console.  The.
CS305j Introduction to Computing File Processing 1 Topic 18 File Processing " We have also obtained a glimpse of another crucial idea about languages and.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
1 Hours question Given a file hours.txt with the following contents: 123 Kim Eric Stef
BUILDING JAVA PROGRAMS CHAPTER 6 File Processing.
1 BUILDING JAVA PROGRAMS CHAPTER 7 LECTURE 7-3: ARRAYS AS PARAMETERS; FILE OUTPUT.
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.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks:
Interactive Programs with Scanner. 2 Input and System.in interactive program: Reads input from the console. –While the program runs, it asks the user.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6: File Processing Lecture 6-2: Advanced file input reading: self-check: #7-11.
1 Building Java Programs Chapter 6 Lecture 6-3: Section Problems reading:
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:
1 Reminder: String Scanners A Scanner can be constructed to tokenize a particular String, such as one line of an input file. Scanner = new Scanner( );
File Processing Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from "We can only.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks:
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-3: Searching Files reading: 6.3, 6.5.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
1 Line-based file processing reading: 6.3 Use this if you seem to need line based processing for some aspects of your program and token based for others.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 6
Output to files reading: 6.4.
Building Java Programs
Hours question Given a file hours.txt with the following contents:
File Input and Output TOPICS File Input Exception Handling File Output.
Line-based file processing
File Input and Output TOPICS File Input Exception Handling File Output.
Topic 20 more file processing
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapters 6 and 7 Line-Based File Input, Arrays reading: , 7.1
Building Java Programs
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
Hours question Given a file hours.txt with the following contents:
Building Java Programs
Building Java Programs
Files Readings: 6.1 – 6.2.
Building Java Programs
Building Java Programs
Topic 19 file input, line based
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Optional Topic: User Input with Scanner
Presentation transcript:

1 Line-based file processing suggested reading:6.3

2 Line-by-line processing Scanners have a method named nextLine that returns text from the input cursor's current position forward to the nearest \n new line character. You can use nextLine to break up a file's contents into each line and examine the lines individually. Reading a file line-by-line, general syntax: Scanner input = new Scanner(new File(" ")); while (input.hasNextLine()) { String line = input.nextLine(); ; }

3 Line-based input The Scanner's nextLine method consumes and returns an entire line of input as a String. The Scanner moves its cursor until it sees a \n new line character, and returns all text that was found. The \n character is consumed but not returned. nextLine is the only non-token-based Scanner method. Recall that the Scanner also has a hasNextLine method. Example: John Smith "Hello world" String line1 = input.nextLine(); 23\t3.14 John Smith\t"Hello world"\n\t\t \n ^ String line2 = input.nextLine(); 23\t3.14 John Smith\t"Hello world"\n\t\t \n ^

4 File processing problem Write a program that reads an message from a text file and turns it into a quoted message by putting a > and space in front of each line. Example input: Kelly, Can you please modify the a5/turnin settings to make CSE 142 Homework 5 due Wednesday, July 27 at 11:59pm instead of due tomorrow at 6pm? Thanks, Joe Example output: > Kelly, > > Can you please modify the a5/turnin settings > to make CSE 142 Homework 5 due Wednesday, > July 27 at 11:59pm instead of due tomorrow > at 6pm? > > Thanks, Joe

5 File processing answer The following code solves the problem: import java.io.*; import java.util.*; public class QuoteMessage { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("message.txt")); while (input.hasNextLine()) { String line = input.nextLine(); System.out.println(">" + line); }

6 Processing tokens of one line Many input files have a data record on each line. The contents of each line contain meaningful tokens. Example file contents: 123 Susan Brad Jennifer Consider the task of computing the total hours worked for each person represented in the above file. Enter a name: Brad Brad (ID#456) worked 36.8 hours (7.36 hours/day) Neither line-based nor token-based processing is quite right, because we want to break the input into tokens. The better solution is a hybrid approach in which we break the input into lines, and then break each line into tokens.

7 Scanners on Strings A Scanner can be constructed to tokenize a particular String, such as one line of an input file. Scanner = new Scanner( ); Example: String text = " hello "; Scanner scan = new Scanner(text); // five tokens We can use this idea to tokenize each line of a file. Scanner input = new Scanner(new File(" ")); while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); ; }

8 Complex input question Write a program that computes the total hours worked and average hours per day for a particular person represented in the following file. Input file contents: 123 Susan Brad Jennifer Example log of execution: Enter a name: Brad Brad (ID#456) worked 36.8 hours (7.36 hours/day)

9 Searching for a line Recall: reading a file line-by-line, general syntax: Scanner input = new Scanner(new File(" ")); while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); ; } If we are looking for a particular line, often we look for the token(s) of interest on each line. If we find the right value, we'll process the rest of the line. Example: If the second token on the line is "Brad", process it.

10 Processing a particular line The following code solves the "hours" problem: Scanner console = new Scanner(System.in); System.out.print("Enter a name: "); String name = console.next(); Scanner input = new Scanner(new File("hours.txt")); while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); int id = lineScan.nextInt(); String thisName = lineScan.next(); // "Brad" double sum = 0.0; int count = 0; if (name.equals(thisName)) { // we found the right person while (lineScan.hasNextDouble()) { sum += lineScan.nextDouble(); count++; } double avg = sum / count; System.out.println(name + " worked " + sum + " hours (" + avg + " hours/day)"); }

11 File processing question Write a program that reads in a file containing pseudo- HTML text, but with the HTML tags missing their brackets. Whenever you see any uppercase token in the file, surround it with, and output the corrected file text to the console. You must retain the original orientation/spacing of the tokens on each line. (Is this problem line-based or token-based?) Input file: HTML HEAD TITLE My web page /TITLE /HEAD BODY P There are pics of my cat here, as well as my B cool /B blog, which contains I awesome /I stuff about my trip to Vegas. /BODY /HTML Output to console: My web page There are pics of my cat here, as well as my cool blog, which contains awesome stuff about my trip to Vegas.

12 File processing solution The following code solves the HTML problem: import java.io.*; import java.util.*; public class WebPage { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("page.html")); while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); while (lineScan.hasNext()) { String token = lineScan.next(); if (token.equals(token.toUpperCase())) { // this is an HTML tag System.out.print(" "); } else { System.out.print(token + " " ); } System.out.println(); }

13 Prompting for a file name Instead of writing the file's name into the program as a String, we can ask the user to tell us the file to use. Here is one case where we may wish to use the nextLine method on the console Scanner, because the file name might have spaces in it. // prompt for the file name Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextLine(); Scanner input = new Scanner(new File(filename));

14 Fixing file-not-found issues What if the user types a file name that does not exist? File objects have an exists method we can use to make sure that the file is found on the system. Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextLine(); File file = new File(filename); while (!file.exists()) { System.out.print("File not found! Try again: "); String filename = console.nextLine(); file = new File(filename); } Scanner input = new Scanner(file); // open the file Output: Type a file name to use: hourz.text File not found! Try again: h0urz.txt File not found! Try again: hours.txt