Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files Section 2.13, Section 8.8.

Slides:



Advertisements
Similar presentations
Click to edit Master title style. Click to edit Master subtitle style.
Advertisements

Computer Programming Lab(7).
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
CPSC150 Week 13 Chapter 12 Exceptions (from slides provided by textbook web site)
18 File handling1June File handling CE : Fundamental Programming Techniques.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files.
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
2-1 CM0551 Week 3 The scanner class – file input A Spelling Checker Time and space requirements for various dictionary structures.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CSC172 Intro Pepper. Goals Reminder of what a class is How to create and use classes How to design classes How to think in terms of objects How to comment.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
CSc2310 tutoring session, week 8 Fall, 2012 Haidong Xue 5:30pm—8:30pm 10/23/2012 and 10/24/2012 -Using Exceptions -Homework 4.
Java Fundamentals 3 Input and Output statements. Standard Output Window Using System.out, we can output multiple lines of text to the standard output.
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.
1 Hours question Given a file hours.txt with the following contents: 123 Kim Eric Stef
File Input/Output. 2Java Programming: From Problem Analysis to Program Design, 3e File Input/Output File: area in secondary storage used to hold information.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
1 BUILDING JAVA PROGRAMS CHAPTER 6 DETAILS OF TOKEN-BASED PROCESSING.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Week 14 - Monday.  What did we talk about last time?  Inheritance.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
CS1020 Data Structures and Algorithms I Lecture Note #16 File Processing.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Introduction to programming in java
For Friday Finish reading chapter 9 WebCT quiz 17.
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.
File Input / Output.
Streams & File Input/Output (I/O)
Reading from a file and Writing to a file
Click to Add Title Click to Add Subtitle.
Click to Add Title Click to Add Subtitle.
User Input You’ve seen this: A Scanner object:
Testing and Exceptions
שימוש במחלקות קיימות מחרוזות, קבצים, וקבלת קלט מהמשתמש
CSS161: Fundamentals of Computing
שימוש במחלקות קיימות מחרוזות, קבצים, וקבלת קלט מהמשתמש
Click to edit Master text styles
שימוש במחלקות קיימות מחרוזות, קבצים, וקבלת קלט מהמשתמש
Click to Add Title Click to Add Subtitle.
Click to Add Title Click to Add Subtitle.
Author names here Author association names here
Click to edit Master text styles
TITLE SLIDE GOES HERE Optional subhead.
File Handling in Java January 19
Click to edit Master text styles
Slide Title Edit Master text styles Second level Third level
ОПШТЕСТВО ТЕМА: МЕСТОТО ВО КОЕ ЖИВЕАМ Скопје
Author names here Author associations here
Author names here Author associations here
Introduction to Java Brief history of Java Sample Java Program
Click to edit Master text styles
CSC1401 Input and Output (with Files)
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Building Java Programs
Author names here Author associations here
Random Numbers while loop
Consider the following code:
Click to edit Master text styles
Text File Input & Output
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files Section 2.13, Section 8.8

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 2 Files To use files, use File class File class can’t read/write To read/write files, use Scanner/PrintWriter classes File input can be text-based (what we’ll do), stream-based

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 3 Text Input Use the Scanner class import java.util.Scanner; java.io.File; Put Scanner activity within try { …} catch (Exception e) {…} Tie object to File object and diskfile name Use next to get next String, nextInt to get nextInt, etc. [Must know order of input] Close the scanner object.

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 4 Text Input try { Scanner s = new Scanner (new File("filename.txt")); while (s.hasNext( )) // read to EOF { String firstS = s.next( ); int secondI = s.nextInt( ); double thirdD = s.nextDouble( ); // do something with what you just read } catch (Exception except) { // do what happens when things go tragically awry System.out.println("Things went tragically awry"); System.exit(1); } you must have new File. you must put Scanner declaration in try- catch means input order is String, int, double for each record }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 5 Text output Use the PrintWriter class. Import java.io.PrintWriter Put inside try { …} catch (Exception e) {…} Tie PrintWriter object to diskfile name Use print, println to write to the object Close the FileWriter.

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 6 Text output try { PrintWriter writer = new PrintWriter("name of file"); while(there is more text to write) {... writer.println(next piece of text);... } writer.close(); } catch(IOException e) { /* something went wrong with accessing the file */ }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 7 Write a program to count number of lines in a file and write the number to an output file java countlines myinfile.txt myoutfile.txt would return 2 if file is: This is a file with two lines. myinfile.txt

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 8 import java.io.*; public class countlines { // all methods that do something inserted here public static void main(String[] args) { if (args.length != 2) { System.out.println ("to run, type: 'java countlines filein fileout'"); System.exit(1); } // create a new countline object with first arg as input file, second as output countlines cl = new countlines(args[0], args[1]); }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 9 // constructor public countlines(String filein, String fileout) { int nbrLines = readfrom(filein); writeTo(fileout, nbrLines); } // write method public void writeTo(String fileout, int nbrLines) { PrintWriter outFile = new PrintWriter(new File(fileout)); fileout.println("The number of lines is " + nbrLines); fileout.close( ); }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 10 Scanner Class: for reading files public int readfrom(String filein) { Scanner scanner; try { scanner = new Scanner(new File(filein)); while (scanner.hasNext) { String line = scanner.nextLine( ); // also next( ), nextInt( ), nextDouble( ) System.out.println(line); // for debugging only; countlines++; } return countlines; } catch (FileNotFoundException ex) { System.out.println("File not found...aborting program."); System.exit(1); } }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 11 Console input: Section 2.13 Scanner class: Java 5 import java.util.*; class MyScanner { public MyScanner ( ) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a number: "); int x = scanner.nextInt(); int y = scanner.nextInt(); System.out.println("The sum of " + x + " + " + y + " is " + (x+y)); }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 12 File input using Scanner import java.util.*; import java.io.*; class MyScanner { public MyScanner ( ) { Scanner scanner; try { scanner = new Scanner(new File("infile.java")); int x = scanner.nextInt( ); int y = scanner.nextInt( ); System.out.println("The sum of " + x + " + " + y + " is " + (x+y)); } catch (FileNotFoundException ex) { System.out.println("File not found...aborting program."); System.exit(1); } }

Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 13 Write a Payroll Program Write a program that reads in a file in the form first last hourlyrate hoursworked exempt, e.g,: Susie Jones N Johnny Jacob Y Jane White N And writes out information to an output file in the form: first last weeklypay, e.g., Susie Jones: Johnny Jacob: Jane White: Your program should get the filein and fileout names from the command line. Print the total payroll for the week in a terminal window. Pay should be figured in the following way: if the employee has worked no overtime, pay is number of hours * hourly rate. Otherwise, if the employee is not exempt, the pay is hourly rate * 40 + hourly rate * 1.5 * hours over 40. If the employee is exempt, the employee receives no overtime (so is paid for no more than 40 hours, less if the employee worked less).