COMP200 INPUT/OUTPUT OOP using Java, based on slides by Shayan - - PowerPoint PPT Presentation

comp200
SMART_READER_LITE
LIVE PREVIEW

COMP200 INPUT/OUTPUT OOP using Java, based on slides by Shayan - - PowerPoint PPT Presentation

1 1 COMP200 INPUT/OUTPUT OOP using Java, based on slides by Shayan Javed 2 Input/Output (IO) 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


slide-1
SLIDE 1

1

COMP200


INPUT/OUTPUT

OOP using Java, based on slides by Shayan Javed

1

slide-2
SLIDE 2

2

Input/Output (IO)

slide-3
SLIDE 3

3

I/O

So far we have looked at modeling classes

slide-4
SLIDE 4

4

I/O

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

slide-5
SLIDE 5

5

Input

3 ways of providing input to the program:

slide-6
SLIDE 6

6

Input

3 ways of providing input to the program:

Pass parameters directly to the program

slide-7
SLIDE 7

7

Input

3 ways of providing input to the program:

Pass parameters directly to the program Command-line input from the user

slide-8
SLIDE 8

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

slide-9
SLIDE 9

9

Passing parameters

When running the program can directly pass

parameters to it

slide-10
SLIDE 10

10

Passing parameters

When running the program can directly pass

parameters to it

java ProgramName parameter1 parameter2 ...

slide-11
SLIDE 11

11

Passing parameters

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

slide-12
SLIDE 12

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

slide-13
SLIDE 13

13

Command-line input

Receive input from the console during

execution

slide-14
SLIDE 14

14

Command-line input

Receive input from the console during

execution

Use the Scanner class

slide-15
SLIDE 15

15

The Scanner class

Used for reading data

slide-16
SLIDE 16

16

The Scanner class

Used for reading data Constructors:

Scanner(InputStream)

■ InputStream = System.in

slide-17
SLIDE 17

17

The Scanner class

Used for reading data Constructors:

Scanner(InputStream)

■ InputStream = System.in

Scanner(String)

slide-18
SLIDE 18

18

The Scanner class

Used for reading data Constructors:

Scanner(InputStream)

■ InputStream = System.in

Scanner(String) Scanner(File)

slide-19
SLIDE 19

19

The Scanner class

Methods:

boolean hasNext() :

If scanner has more tokens

slide-20
SLIDE 20

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

slide-21
SLIDE 21

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)

slide-22
SLIDE 22

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

slide-23
SLIDE 23

23

Command-line input

Use the “next..” methods to read from the standard input

slide-24
SLIDE 24

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));

slide-25
SLIDE 25

25

File Input

Ability to read files essential to any language.

slide-26
SLIDE 26

26

File Input

Ability to read files essential to any language. Two ways to store data:

Text format:

slide-27
SLIDE 27

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

slide-28
SLIDE 28

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

slide-29
SLIDE 29

29

The File class

java.io package Represents a “file” object Used for input/output through data streams,

the file system and serialization.

slide-30
SLIDE 30

30

The File class

Constructors:

File(pathname: String):

Creates a File object for the specified

  • pathname. pathname = directory or file
slide-31
SLIDE 31

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.

slide-32
SLIDE 32

32

The File class

Methods:

boolean exists() :

If the file exists

slide-33
SLIDE 33

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

slide-34
SLIDE 34

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

slide-35
SLIDE 35

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

slide-36
SLIDE 36

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

slide-37
SLIDE 37

37

Reading Files

Use the Scanner class new Scanner(File)

slide-38
SLIDE 38

38

Reading Files

How does Scanner really work?

slide-39
SLIDE 39

39

Reading Files

How does Scanner really work? Breaks file contents into tokens

Uses a delimiter

slide-40
SLIDE 40

40

Reading Files

How does Scanner really work? Breaks file contents into tokens

Uses a delimiter Delimiter by default is whitespace

slide-41
SLIDE 41

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

slide-42
SLIDE 42

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

slide-43
SLIDE 43

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()); }

slide-44
SLIDE 44

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

slide-45
SLIDE 45

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

slide-46
SLIDE 46

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(); }

slide-47
SLIDE 47

47

Reading files

Have to be careful. Suppose a file contains

the line:

34 567

slide-48
SLIDE 48

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();

slide-49
SLIDE 49

49

Reading files

Scanner scanner = new Scanner(“file.txt”);

Treats the String “file.txt” as the source, NOT the file “file.txt”

slide-50
SLIDE 50

50

Writing Files

Use the PrintWriter class

slide-51
SLIDE 51

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

slide-52
SLIDE 52

52

The PrintWriter class

Methods:

void print(String) :

Writes a String

slide-53
SLIDE 53

53

The PrintWriter class

Methods:

void print(String) :

Writes a String

void print(int) :

Writes an int

void print(float) :

Writes a float

slide-54
SLIDE 54

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

slide-55
SLIDE 55

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

slide-56
SLIDE 56

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.

slide-57
SLIDE 57

57

Writing Files

PrintWriter output = null; try {

  • utput = new PrintWriter(new File(“test”));

// creates a file if it does not exist; // discards the current content if the file exists

  • utput.print("John T Smith "); output.println(90);
  • utput.print("Eric K Jones "); output.println(85);
  • utput.flush();

} catch(IOException ioe) { System.out.println(ioe.toString()); } finally { if (output != null) output.close(); }

slide-58
SLIDE 58

58

Writing Files

Problem: What if you want to append to the

file not replace it?

slide-59
SLIDE 59

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.

slide-60
SLIDE 60

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

slide-61
SLIDE 61

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

slide-62
SLIDE 62

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)

slide-63
SLIDE 63

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) )

slide-64
SLIDE 64

64

Writing Files

PrintWriter output = null; try {

  • utput = new PrintWriter(new File(“test”));

// creates a file if it does not exist; // discards the current content if the file exists

  • utput.print("John T Smith "); output.println(90);
  • utput.print("Eric K Jones "); output.println(85);
  • utput.flush();

} catch(IOException ioe) { System.out.println(ioe.toString()); } finally { if (output != null) output.close(); }

slide-65
SLIDE 65

65

Writing Files – Append

PrintWriter output = null; try {

  • utput = 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

  • utput.print("John T Smith "); output.println(90);
  • utput.print("Eric K Jones "); output.println(85);
  • utput.flush();

} catch(IOException ioe) { System.out.println(ioe.toString()); } finally { if (output != null) output.close(); }

slide-66
SLIDE 66

66

Summary

Use Scanner for reading from command-line

and files.

Based on delimiters

Use PrintWriter for writing to files