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

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

C17a: Exception and Text File I/O

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Reading Input from Text File

Java Input/Output. 11 April 2013 OSU CSE 1

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Unit 10: exception handling and file I/O

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

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

Chapter 9 Strings and Text I/O

תוכנה 1 4 תרגול מס' שימוש במחלקות קיימות: קלט/פלט )IO(

JAVA - FILE CLASS. The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object

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

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Computer Science is...

ing execution. That way, new results can be computed each time the Class The Scanner

CS 211: Existing Classes in the Java Library

CS Week 11. Jim Williams, PhD

Reading Text Files. 1 Reading from text files: Scanner

CS 200 File Input and Output Jim Williams, PhD

Simple Java Input/Output

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

EXCEPTIONS. Fundamentals of Computer Science I

CS Programming I: File Input / Output

Excep&ons and file I/O

Object-Oriented Programming in Java

Building Java Programs

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

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

CS Programming I: File Input / Output

Text User Interfaces. Keyboard IO plus

Building Java Programs

CS 251 Intermediate Programming Java I/O Streams

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

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

CSC 1214: Object-Oriented Programming

IT101. File Input and Output

CS244 Advanced Programming Applications

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

Data Structures. 03 Streams & File I/O

HST 952. Computing for Biomedical Scientists Lecture 8

A token is a sequence of characters not including any whitespace.

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

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Streams and File I/O

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

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

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Input-Output and Exception Handling

PIC 20A Streams and I/O

AP Computer Science Unit 1. Programs

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

Program 12 - Spring 2018

COMP-202 Unit 9: Exceptions

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Object-Oriented Programming Design. Topic : Streams and Files

Streams and File I/O

CSCI 1103: File I/O, Scanner, PrintWriter

CS 1301 Ch 8, Handout 3

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

The File Class. File I/O. An abstract representation of file and directory pathnames. Construction: File(String pathname)

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Building Java Programs

Here is a hierarchy of classes to deal with Input and Output streams.

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

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

Chapter 4: Loops and Files

More on Java. Object-Oriented Programming

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CSCI 161 Introduction to Computer Science

Starting Out with Java: From Control Structures Through Objects Sixth Edition

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

Motivations. Chapter 12 Exceptions and File Input/Output

Classes Basic Overview

CSPP : Introduction to Object-Oriented Programming

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Streams and File I/O

Classes and Objects Part 1

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Exceptions and Working with Files

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.

CIS 110: Introduction to Computer Programming

CSCI 1103: File I/O, Scanner, PrintWriter

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Experiment No: Group B_4

Objec-ves JAR FILES. Jar files. Excep-ons. Files Streams. Ø Wrap up Ø Why Excep-ons? 9/30/16. Oct 3, 2016 Sprenkle - CSCI209 1

CSE 21 Intro to Computing II. JAVA Objects: String & Scanner

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

Give one example where you might wish to use a three dimensional array

Mandatory Assignment 1, INF 4130, 2017

Input/Output (I/0) What is File I/O? Writing to a File. Writing to Standard Output. CS111 Computer Programming

输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream

COMP102: Test. 26 April, 2006

Chapter 4: Loops and Files

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

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Transcription:

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

Input/Output (IO) 2

3 I/O So far we have looked at modeling classes

4 I/O So far we have looked at modeling classes Not much in the way of Input...

5 Input 3 ways of providing input to the program:

6 Input 3 ways of providing input to the program:! Pass parameters directly to the program

7 Input 3 ways of providing input to the program:! Pass parameters directly to the program! Command-line input from the user

8 Input 3 ways of providing input to the program:! Pass parameters directly to the program! Command-line input from the user! Reading in files

9 Passing parameters When running the program can directly pass parameters to it

10 Passing parameters When running the program can directly pass parameters to it java ProgramName parameter1 parameter2...

11 Passing parameters public static void main(string[] args) { // args is the array of all parameters // args[0] would be the first parameter }

12 Passing parameters public static void main(string[] args) { // args is the array of all parameters // args[0] would be the first parameter } Let s look at an example

13 Command-line input Receive input from the console during execution

14 Command-line input Receive input from the console during execution Use the Scanner class

15 The Scanner class Used for reading data

16 The Scanner class Used for reading data Constructors:! Scanner(InputStream) InputStream = System.in

17 The Scanner class Used for reading data Constructors:! Scanner(InputStream) InputStream = System.in! Scanner(String)

18 The Scanner class Used for reading data Constructors:! Scanner(InputStream) InputStream = System.in! Scanner(String)! Scanner(File)

19 The Scanner class Methods:! boolean hasnext() : If scanner has more tokens

20 The Scanner class Methods:! boolean hasnext() : If scanner has more tokens! String next() : Returns the next String! int nextint() : Returns the next int! double nextdouble() : Returns the next double

21 The Scanner class Methods:! boolean hasnext() : If scanner has more tokens! String next() : Returns the next String! int nextint() : Returns the next int! double nextdouble() : Returns the next double! void usedelimiter(pattern: String) : Set s the delimiting pattern ( by default)

22 The Scanner class Methods:! boolean hasnext() : If scanner has more tokens! String next() : Returns the next String! int nextint() : Returns the next int! double nextdouble() : Returns the next double! void usedelimiter(pattern: String) : Set s the delimiting pattern ( by default)! void close(): Closes the Scanner

23 Command-line input Use the next.. methods to read from the standard input

24 Command-line input Use the next.. methods to read from the standard input import java.util.scanner; Scanner scanner = new Scanner(System.in); System.out.print( Enter number1: ); double number1 = scanner.nextdouble(); System.out.print( Enter number2: ); double number2 = scanner.nextdouble(); System.out.println( The addition of the two numbers: + (number1 + number2));

25 File Input Ability to read files essential to any language.

26 File Input Ability to read files essential to any language. Two ways to store data:! Text format:

27 File Input Ability to read files essential to any language. Two ways to store data:! Text format: Human-readable form Can be read by text editors

28 File Input Ability to read files essential to any language. Two ways to store data:! Text format: Human-readable form Can be read by text editors! Binary format: Used for executable programs Cannot be read by text editors

29 The File class java.io package Represents a file object Used for input/output through data streams, the file system and serialization.

30 The File class Constructors:! File(pathname: String): Creates a File object for the specified pathname. pathname = directory or file

31 The File class Constructors:! File(pathname: String): Creates a File object for the specified pathname. pathname = directory or file! File(parent: String, child: String): Creates a File object for the child under the directory parent. child may be a filename or subdirectory.

32 The File class Methods:! boolean exists() : If the file exists

33 The File class Methods:! boolean exists() : If the file exists! boolean canread() : If the file exists and we can read it! boolean canwrite() : If the file exists and we can write to it

34 The File class Methods:! boolean exists() : If the file exists! boolean canread() : If the file exists and we can read it! boolean canwrite() : If the file exists and we can write to it! void isdirectory() : if the object is a directory! void isfile() : if the object is a file

35 The File class Methods:! boolean exists() : If the file exists! boolean canread() : If the file exists and we can read it! boolean canwrite() : If the file exists and we can write to it! void isdirectory() : if the object is a directory! void isfile() : if the object is a file! String getname() : Returns the name of the file

36 The File class Methods:! boolean exists() : If the file exists! boolean canread() : If the file exists and we can read it! boolean canwrite() : If the file exists and we can write to it! void isdirectory() : if the object is a directory! void isfile() : if the object is a file! String getname() : Returns the name of the file! boolean delete() : Deletes the file and returns true if succeeded! renameto (dest: File) : Tries to rename the file and returns true if succeeded

37 Reading Files Use the Scanner class new Scanner(File)

38 Reading Files How does Scanner really work?

39 Reading Files How does Scanner really work? Breaks file contents into tokens! Uses a delimiter

40 Reading Files How does Scanner really work? Breaks file contents into tokens! Uses a delimiter! Delimiter by default is whitespace

41 Reading Files How does Scanner really work? Breaks file contents into tokens! Uses a delimiter! Delimiter by default is whitespace Reads a token, converts it to the required type

42 Reading Files How does Scanner really work? Breaks file contents into tokens! Uses a delimiter! Delimiter by default is whitespace Reads a token, converts it to the required type Can change the delimiter usedelimiter() method

43 Reading Files // Reads in the file and outputs all the tokens Scanner input = new Scanner(new File( test.txt )); while (input.hasnext()) { } System.out.println(input.next());

44 Reading Files // Reads in the file and outputs all the tokens Scanner input = new Scanner(new File( test.txt )); while (input.hasnext()) { } System.out.println(input.next()); ERROR WON T COMPILE

45 Reading Files // Reads in the file and outputs all the tokens Scanner input = new Scanner(new File( test.txt )); while (input.hasnext()) { } System.out.println(input.next()); ERROR WON T COMPILE The constructor throws a FileNotFoundException

46 Reading Files // Reads in the file and outputs all the tokens try { Scanner input = new Scanner(new File( test.txt )); while (input.hasnext()) { System.out.println(input.next()); } } catch (FileNotFoundException fe) { fe.printstacktrace(); }

47 Reading files Have to be careful. Suppose a file contains the line:! 34 567

48 Reading files Have to be careful. Suppose a file contains the line:! 34 567 What will be the contents of intvalue and line after the following code is executed? Scanner in = new Scanner(new File( test.txt )); int intvalue = in.nextint(); String line = in.nextline();

49 Reading files Scanner scanner = new Scanner( file.txt ); Treats the String file.txt as the source, NOT the file file.txt

50 Writing Files Use the PrintWriter class

51 Writing Files Use the PrintWriter class Constructors:! PrintWriter(File file): Creates a PrintWriter for the specified File! PrintWriter(String name): Creates a PrintWriter for the specified File with the name

52 The PrintWriter class Methods:! void print(string) : Writes a String

53 The PrintWriter class Methods:! void print(string) : Writes a String! void print(int) : Writes an int! void print(float) : Writes a float

54 The PrintWriter class Methods:! void print(string) : Writes a String! void print(int) : Writes an int! void print(float) : Writes a float! void println(string) : Writes a String but also adds a line separator

55 The PrintWriter class Methods:! void print(string) : Writes a String! void print(int) : Writes an int! void print(float) : Writes a float! void println(string) : Writes a String but also adds a line separator! void flush() : Flushes the output stream. Ensures writing to the file

56 The PrintWriter class Methods:! void print(string) : Writes a String! void print(int) : Writes an int! void print(float) : Writes a float! void println(string) : Writes a String but also adds a line separator! void flush() : Flushes the output stream. Ensures writing to the file! void close() : Closes the output stream.

57 Writing Files PrintWriter output = null; try { output = new PrintWriter(new File( test )); // creates a file if it does not exist; // discards the current content if the file exists output.print("john T Smith "); output.println(90); output.print("eric K Jones "); output.println(85); output.flush(); } catch(ioexception ioe) { System.out.println(ioe.toString()); } finally { if (output!= null) output.close(); }

58 Writing Files Problem: What if you want to append to the file not replace it?

59 Writing Files Problem: What if you want to append to the file not replace it? Solution 1: Read the whole file, then write it back.

60 Writing Files Problem: What if you want to append to the file not replace it? Solution 1: Read the whole file, then write it back.! Cumbersome and too much work

61 Writing Files Problem: What if you want to append to the file not replace it? Solution 1: Read the whole file, then write it back.! Cumbersome and too much work Solution 2: Use the FileWriter class

62 Writing Files Problem: What if you want to append to the file not replace it? Solution 1: Read the whole file, then write it back.! Cumbersome and too much work Solution 2: Use the FileWriter class! FileWriter(File file, boolean append)

63 Writing Files Problem: What if you want to append to the file not replace it? Solution 1: Read the whole file, then write it back.! Cumbersome and too much work Solution 2: Use the FileWriter class! FileWriter(File file, boolean append)! PrintWriter pw = new PrintWriter(new FileWriter(file, true) )

64 Writing Files PrintWriter output = null; try { output = new PrintWriter(new File( test )); // creates a file if it does not exist; // discards the current content if the file exists output.print("john T Smith "); output.println(90); output.print("eric K Jones "); output.println(85); output.flush(); } catch(ioexception ioe) { System.out.println(ioe.toString()); } finally { if (output!= null) output.close(); }

65 Writing Files Append PrintWriter output = null; try { output = new PrintWriter( new FileWriter(new File( test ),true) ); // creates a file if it does not exist; // appends to the current content if the file exists output.print("john T Smith "); output.println(90); output.print("eric K Jones "); output.println(85); output.flush(); } catch(ioexception ioe) { System.out.println(ioe.toString()); } finally { if (output!= null) output.close(); }

66 Summary Use Scanner for reading from command-line and files.! Based on delimiters Use PrintWriter for writing to files