SWEN20003 Object Oriented Software Development 0.5 cm Input and Output
SWEN20003
Object Oriented Software Development
Input and Output
Shanika Karunasekera
.au
University of Melbourne
c© University of Melbourne 2020
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 1 / 67
The Road So Far
Subject Introduction
A Quick Tour of Java
Classes and Objects
Arrays and Strings
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 2 / 67
Lecture Objectives
Upon completion of this topic you will be able to:
Accept input to your programs through:
I Command line arguments
I User input
I Files
Write output from your programs through:
I Standard output (terminal)
I Files
Use files to store and retrieve data during program execution
Manipulate data in files (i.e. for computation)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 3 / 67
Input:
Command Line Arguments
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 4 / 67
Command Line Arguments
Let’s take a look back at “Hello World”
public static void main(String[] args)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 5 / 67
Command Line Arguments
Let’s take a look back at “Hello World”
public static void main(String[] args)
What exactly is this?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 5 / 67
Command Line Arguments
void main(String[] args)
args is a variable that stores command line arguments
String[] means that args is an array of Strings
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 6 / 67
Command Line Arguments
void main(String[] args)
args is a variable that stores command line arguments
String[] means that args is an array of Strings
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 6 / 67
Entering Arguments – Terminal
If you compile and run Java from the terminal the syntax is very similar to C.
java MyProg Hello World 10
This fills the args variable with three elements, “Hello”, “World” and “10”
For multiword Strings, remember to use quotes
Also note that “10” is a String, not an int
1 java MyProg “Hello World” 10
This fills the args variable with two elements, “Hello World” and “10”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 67
Entering Arguments – Terminal
If you compile and run Java from the terminal the syntax is very similar to C.
java MyProg Hello World 10
This fills the args variable with three elements, “Hello”, “World” and “10”
For multiword Strings, remember to use quotes
Also note that “10” is a String, not an int
1 java MyProg “Hello World” 10
This fills the args variable with two elements, “Hello World” and “10”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 67
Entering Arguments – Terminal
If you compile and run Java from the terminal the syntax is very similar to C.
java MyProg Hello World 10
This fills the args variable with three elements, “Hello”, “World” and “10”
For multiword Strings, remember to use quotes
Also note that “10” is a String, not an int
1 java MyProg “Hello World” 10
This fills the args variable with two elements, “Hello World” and “10”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 67
Entering Arguments – Terminal
If you compile and run Java from the terminal the syntax is very similar to C.
java MyProg Hello World 10
This fills the args variable with three elements, “Hello”, “World” and “10”
For multiword Strings, remember to use quotes
Also note that “10” is a String, not an int
1 java MyProg “Hello World” 10
This fills the args variable with two elements, “Hello World” and “10”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 67
Entering Arguments – Terminal
If you compile and run Java from the terminal the syntax is very similar to C.
java MyProg Hello World 10
This fills the args variable with three elements, “Hello”, “World” and “10”
For multiword Strings, remember to use quotes
Also note that “10” is a String, not an int
1 java MyProg “Hello World” 10
This fills the args variable with two elements, “Hello World” and “10”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 67
Entering Arguments – IntelliJ
Because IDEs do a lot of “behind the scenes” magic, command line
arguments are a bit different
In IntelliJ we have to set the “run configuration” to provide command line
arguments
You can find a walkthrough of the process here
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 8 / 67
https://www.jetbrains.com/help/idea/creating-and-editing-run-debug-configurations.html
What Next?
How do you actually use the arguments once they are put into the program?
Access the elements of the array by indexing
Identical syntax to accessing array elements in C, or list/tuple elements in
Python
java MyProg “An” “Argument” “This is another argument”
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
“An”
“Argument”
“This is another argument”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 9 / 67
Keyword
Command Line Argument: Information or data provided to a program when it is
executed, accessible through the args variable.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 10 / 67
Assess Yourself
Write a program that creates a Person object from three command line
arguments, and then outputs the object as a String.
A Person is created from three arguments:
int age – age, in years
double height – height, in metres
String name – name, as a String
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 11 / 67
Assess Yourself
1 public class Program {
2 public static void main(String[] args) {
3 int age = Integer.parseInt(args[0]);
4 double height = Double.parseDouble(args[1]);
5 String name = args[2];
6
7 Person person = new Person(age, height, name);
8 System.out.println(person);
9 }
10 }
Example input:
java Program 27 1.68 “Emily Brown”
Example output:
“Emily Brown – age: 27, height: 168cm”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 12 / 67
Assess Yourself
1 public class Program {
2 public static void main(String[] args) {
3 int age = Integer.parseInt(args[0]);
4 double height = Double.parseDouble(args[1]);
5 String name = args[2];
6
7 Person person = new Person(age, height, name);
8 System.out.println(person);
9 }
10 }
Example input:
java Program 27 1.68 “Emily Brown”
Example output:
“Emily Brown – age: 27, height: 168cm”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 12 / 67
Assess Yourself
1 public class Program {
2 public static void main(String[] args) {
3 int age = Integer.parseInt(args[0]);
4 double height = Double.parseDouble(args[1]);
5 String name = args[2];
6
7 Person person = new Person(age, height, name);
8 System.out.println(person);
9 }
10 }
Example input:
java Program 27 1.68 “Emily Brown”
Example output:
“Emily Brown – age: 27, height: 168cm”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 12 / 67
Assess Yourself
What are the disadvantage of command line arguments?
When is it appropriate to use them?
When should you use it in the test/exam?
Let’s look at the interactive alternative
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 67
Assess Yourself
No interactivity
When is it appropriate to use them?
When should you use it in the test/exam?
Let’s look at the interactive alternative
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 67
Assess Yourself
No interactivity
Usually for program configuration
When should you use it in the test/exam?
Let’s look at the interactive alternative
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 67
Assess Yourself
No interactivity
Usually for program configuration
Only when the question tells you! Probably never.
Let’s look at the interactive alternative
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 67
Assess Yourself
No interactivity
Usually for program configuration
Only when the question tells you! Probably never.
Let’s look at the interactive alternative
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 67
Input:
Scanner
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 14 / 67
Scanner
Java offers a much more powerful approach to input than C and Python
called the Scanner
We’ll look at some of the capabilities, but check out the full documentation
here
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 15 / 67
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Scanner
Need to import the library first
import java.util.Scanner;
Then we create the Scanner
Scanner scanner = new Scanner(System.in);
Only ever create one Scanner for each program, or bad things happen
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 16 / 67
Creating a Scanner
Scanner scanner = new Scanner(System.in);
The stream/pipe to receive data from, in this case standard input (the
terminal)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 17 / 67
Creating a Scanner
Scanner scanner = new Scanner(System.in);
The stream/pipe to receive data from, in this case standard input (the
terminal)
Keyword
System.in: An object representing the standard input stream, or the command
line/terminal.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 17 / 67
Using a Scanner
Once we’ve created the Scanner, what do we do with it?
Scanner has a number of methods used to read data
The obvious first:
String s = scanner.nextLine();
Reads a single line of text, up until a “return” or newline character
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 18 / 67
Using a Scanner
Once we’ve created the Scanner, what do we do with it?
Scanner has a number of methods used to read data
The obvious first:
String s = scanner.nextLine();
Reads a single line of text, up until a “return” or newline character
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 18 / 67
Using a Scanner
Once we’ve created the Scanner, what do we do with it?
Scanner has a number of methods used to read data
The obvious first:
String s = scanner.nextLine();
Reads a single line of text, up until a “return” or newline character
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 18 / 67
Using a Scanner
Once we’ve created the Scanner, what do we do with it?
Scanner has a number of methods used to read data
The obvious first:
String s = scanner.nextLine();
Reads a single line of text, up until a “return” or newline character
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 18 / 67
Using a Scanner
But there’s more:
boolean b = scanner.nextBoolean();
int i = scanner.nextInt();
double d = scanner.nextDouble();
Reads a single value that matches the method name (boolean, int, etc…)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 19 / 67
Using a Scanner
But there’s more:
boolean b = scanner.nextBoolean();
int i = scanner.nextInt();
double d = scanner.nextDouble();
Reads a single value that matches the method name (boolean, int, etc…)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 19 / 67
Using a Scanner
But there’s more:
boolean b = scanner.nextBoolean();
int i = scanner.nextInt();
double d = scanner.nextDouble();
Reads a single value that matches the method name (boolean, int, etc…)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 19 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner1 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println(“Enter your input: “);
8 double d = scanner.nextDouble();
9 String s1 = scanner.next();
10 String s2 = scanner.nextLine();
11
12 System.out.format(“%3.2f,%s,%s”, d, s2, s1);
13 }
14 }
Input: 5.2 Hello,World Are there any more words?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 20 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner1 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println(“Enter your input: “);
8 double d = scanner.nextDouble();
9 String s1 = scanner.next();
10 String s2 = scanner.nextLine();
11
12 System.out.format(“%3.2f,%s,%s”, d, s2, s1);
13 }
14 }
Input: 5.2 Hello,World Are there any more words?
Output: 5.20, Are there any more words?,Hello,World
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 20 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner2 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println(“Enter your input: “);
8 double d = scanner.nextDouble();
9 float f = scanner.nextFloat();
10 int i = scanner.nextInt();
11
12 System.out.format(“%3.2f , %3.2f , %3d”, d, f, i);
13 }
14 }
Input: 5 6.7 7.2
Output:
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 21 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner2 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println(“Enter your input: “);
8 double d = scanner.nextDouble();
9 float f = scanner.nextFloat();
10 int i = scanner.nextInt();
11
12 System.out.format(“%3.2f , %3.2f , %3d”, d, f, i);
13 }
14 }
Input: 5 6.7 7.2
Output: Error
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 21 / 67
Pitfall: nextXXX
Scanner does not automatically downcast (i.e. float to int)
When using nextXXX, be sure that the input matches what is expected by
your code!
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 22 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner3 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println(“Enter your input: “);
8 double d = scanner.nextDouble();
9 String s1 = scanner.nextLine();
10 String s2 = scanner.nextLine();
11
12 System.out.format(“%3.2f , %s , %s”, d, s1, s2);
13 }
14 }
Input: 5
6.7
7.2
Output:
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 23 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner3 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println(“Enter your input: “);
8 double d = scanner.nextDouble();
9 String s1 = scanner.nextLine();
10 String s2 = scanner.nextLine();
11
12 System.out.format(“%3.2f , %s , %s”, d, s1, s2);
13 }
14 }
Input: 5
6.7
7.2
Output: 5.00, ,6.7
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 23 / 67
Pitfall: Mixing nextXXX with nextLine
nextLine is the only method that “eats” newline characters
In some cases, you may have to follow nextXXX with nextLine, if your input
is on multiple lines
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 24 / 67
Other Features
scanner.hasNext()
scanner.hasNextXXX()
Keyword
.hasNext: Returns true if there is any input to be read
Keyword
.hasNextXXX: Returns true if the next “token” matches XXX
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 25 / 67
Assess Yourself
Write a program that accepts three user inputs, creates an IMDB entry for an
Actor, and prints the object:
String name – the name of a character in a movie/TV show
double rating – a rating for that character
String review – a review of that character
Here is an example of the output format:
“You gave Tony Stark a rating of 9.20/10”
“Your review: ‘I wish I was like Tony Stark…'”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 26 / 67
Assess Yourself
1 public class Actor {
2 public static final int MAX_RATING = 10;
3
4 public String name;
5 public double rating;
6 public String review;
7
8 public Actor(String name, double rating, String review) {
9 this.name = name;
10 this.rating = rating;
11 this.review = review;
12 }
13
14 public String toString() {
15 return String.format(“You gave %s a rating of %f/%d\n”,
16 name, rating, MAX_RATING)
17 + String.format(“Your review: ‘%s'”, review);
18 }
19 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 27 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class TestScanner4 {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 String name = scanner.nextLine();
8
9 double rating = scanner.nextDouble();
10 scanner.nextLine();
11
12 String comment = scanner.nextLine();
13
14 Actor actor = new Actor(name, rating, comment);
15 System.out.println(actor);
16 }
17 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 28 / 67
Input:
Reading Files
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 29 / 67
Reading Files
1 import java.io.FileReader;
2 import java.io.BufferedReader;
3 import java.io.IOException;
4
5 public class ReadFile1 {
6 public static void main(String[] args) {
7
8 try (BufferedReader br =
9 new BufferedReader(new FileReader(“test.txt”))) {
10
11 String text = null;
12
13 while ((text = br.readLine()) != null) {
14 System.out.println(text);
15 }
16 } catch (Exception e) {
17 e.printStackTrace();
18 }
19 }
20 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 30 / 67
Reading Files – Classes
try (BufferedReader br = new BufferedReader(new FileReader(“test.txt”)))
Creates two objects:
I FileReader – A low level file (“test.txt”) for simple character reading
I BufferedReader – A higher level file that permits reading Strings, not just
characters
try/catch exception handling statement – will learn properly under
exceptions
br is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 67
Reading Files – Classes
try (BufferedReader br = new BufferedReader(new FileReader(“test.txt”)))
Creates two objects:
I FileReader – A low level file (“test.txt”) for simple character reading
I BufferedReader – A higher level file that permits reading Strings, not just
characters
try/catch exception handling statement – will learn properly under
exceptions
br is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 67
Reading Files – Classes
try (BufferedReader br = new BufferedReader(new FileReader(“test.txt”)))
Creates two objects:
I FileReader – A low level file (“test.txt”) for simple character reading
I BufferedReader – A higher level file that permits reading Strings, not just
characters
try/catch exception handling statement – will learn properly under
exceptions
br is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 67
Reading Files – Classes
try (BufferedReader br = new BufferedReader(new FileReader(“test.txt”)))
Creates two objects:
I FileReader – A low level file (“test.txt”) for simple character reading
I BufferedReader – A higher level file that permits reading Strings, not just
characters
try/catch exception handling statement – will learn properly under
exceptions
br is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 67
Reading Files – Classes
try (BufferedReader br = new BufferedReader(new FileReader(“test.txt”)))
Creates two objects:
I FileReader – A low level file (“test.txt”) for simple character reading
I BufferedReader – A higher level file that permits reading Strings, not just
characters
try/catch exception handling statement – will learn properly under
exceptions
br is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 67
Reading Files – Methods
while ((text = br.readLine()) != null)
br.readLine(): Reads a single line from the file
text =: Assigns that line of text to a variable
!= null: Then check if anything was actually read
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 32 / 67
Reading Files – Methods
while ((text = br.readLine()) != null)
br.readLine(): Reads a single line from the file
text =: Assigns that line of text to a variable
!= null: Then check if anything was actually read
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 32 / 67
Reading Files – Methods
while ((text = br.readLine()) != null)
br.readLine(): Reads a single line from the file
text =: Assigns that line of text to a variable
!= null: Then check if anything was actually read
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 32 / 67
Reading Files – Errors
catch (IOException e) {
e.printStackTrace();
}
catch – Acts as a safeguard to potential errors, prints an error message if
anything goes wrong; more on Exceptions later
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 33 / 67
Reading Files – Libraries
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
All the classes that make the example go; these make file input possible
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 34 / 67
Reading Files – Scanner
1 import java.io.FileReader;
2 import java.util.Scanner;
3 import java.io.IOException;
4
5 public class ReadFile2 {
6 public static void main(String[] args) {
7
8 try (Scanner file = new Scanner(new FileReader(“test.txt”))) {
9 while (file.hasNextLine()) {
10 System.out.println(file.nextLine());
11 }
12 } catch (Exception e) {
13 e.printStackTrace();
14 }
15 }
16 }
Works the same as BufferedReader, but allows us to parse the text, as well
as read it
Smaller buffer size (internal memory), slower, works on smaller files
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 35 / 67
Assess Yourself
Write a program that reads a file and counts the number of words in the file.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 36 / 67
Assess Yourself
1 import java.io.FileReader;
2 import java.io.BufferedReader;
3 import java.io.IOException;
4
5 public class WordCount {
6 public static void main(String[] args) {
7
8 try (BufferedReader br =
9 new BufferedReader(new FileReader(“test.txt”))) {
10 String text;
11 int count = 0;
12
13 while ((text = br.readLine()) != null) {
14 String words[] = text.split(” “);
15
16 count += words.length;
17 }
18
19 System.out.println(“# Words = ” + count);
20 } catch (Exception e) {
21 e.printStackTrace();
22 }
23
24 }
25 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 37 / 67
Assess Yourself
Write a program that reads a html file and counts the number of lines that have
in the file.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 38 / 67
Assess Yourself
1 import java.io.FileReader;
2 import java.io.BufferedReader;
3 import java.io.IOException;
4
5 public class CountHeaders {
6 public static void main(String[] args) {
7
8 try (BufferedReader br =
9 new BufferedReader(new FileReader(“test.html”))) {
10
11 String text;
12
13 int count = 0;
14
15 while ((text = br.readLine()) != null) {
16 count = text.contains(“
“) ? count + 1 : count;
17 }
18
19 System.out.println(“# Headers: ” + count);
20 } catch (Exception e) {
21 e.printStackTrace();
22 }
23
24 }
25 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 39 / 67
Assess Yourself
What does the following program do?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 40 / 67
Assess Yourself
1 import java.io.FileReader;
2 import java.io.BufferedReader;
3 import java.io.IOException;
4
5 public class ReadCSV {
6 public static void main(String[] args) {
7
8 try (BufferedReader br =
9 new BufferedReader(new FileReader(“recipe.csv”))) {
10 String text;
11 int count = 0;
12
13 while ((text = br.readLine()) != null) {
14 String cells[] = text.split(“,”);
15
16 String ingredient = cells[0];
17 double cost = Double.parseDouble(cells[1]);
18 int quantity = Integer.parseInt(cells[2]);
19
20 System.out.format(“%d %s will cost $%.2f\n”, quantity,
21 ingredient, cost*quantity);
22 }
23 } catch (Exception e) {
24 e.printStackTrace();
25 }
26
27 }
28 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 41 / 67
Reading CSV files
CSV = Comma Separated Value
Somewhat equivalent to a spreadsheet
Usually contains a header row to explain columns
Example:
Ingredient,Cost,Quantity
Bananas,9.2,4
Eggs,1,6
Required knowledge for Projects!
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 42 / 67
Output:
Writing Files
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 43 / 67
File Output
1 import java.io.FileWriter;
2 import java.io.PrintWriter;
3 import java.io.IOException;
4
5 public class FileWrite1 {
6 public static void main(String[] args) {
7 try (PrintWriter pw =
8 new PrintWriter(new FileWriter(“testOut.txt”))) {
9
10 pw.println(“Hello World”);
11 pw.format(“My least favourite device is %s and its price is $%d”,
12 “iPhone”, 100000);
13
14 } catch (IOException e) {
15 e.printStackTrace();
16 }
17 }
18 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 44 / 67
File Output – Classes
try (PrintWriter pw = new PrintWriter(new FileWriter(“test.txt”)))
Creates two objects:
I FileWriter – A low level file (“test.txt”) for simple character output, used
to create…
I PrintWriter – A higher level file that allows more sophisticated formatting
(same methods as System.out)
try will automatically close the file once we’re done
pw is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 45 / 67
File Output – Classes
try (PrintWriter pw = new PrintWriter(new FileWriter(“test.txt”)))
Creates two objects:
I FileWriter – A low level file (“test.txt”) for simple character output, used
to create…
I PrintWriter – A higher level file that allows more sophisticated formatting
(same methods as System.out)
try will automatically close the file once we’re done
pw is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 45 / 67
File Output – Classes
try (PrintWriter pw = new PrintWriter(new FileWriter(“test.txt”)))
Creates two objects:
I FileWriter – A low level file (“test.txt”) for simple character output, used
to create…
I PrintWriter – A higher level file that allows more sophisticated formatting
(same methods as System.out)
try will automatically close the file once we’re done
pw is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 45 / 67
File Output – Classes
try (PrintWriter pw = new PrintWriter(new FileWriter(“test.txt”)))
Creates two objects:
I FileWriter – A low level file (“test.txt”) for simple character output, used
to create…
I PrintWriter – A higher level file that allows more sophisticated formatting
(same methods as System.out)
try will automatically close the file once we’re done
pw is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 45 / 67
File Output – Classes
try (PrintWriter pw = new PrintWriter(new FileWriter(“test.txt”)))
Creates two objects:
I FileWriter – A low level file (“test.txt”) for simple character output, used
to create…
I PrintWriter – A higher level file that allows more sophisticated formatting
(same methods as System.out)
try will automatically close the file once we’re done
pw is our file variable
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 45 / 67
File Output – Methods
pw.print(“Hello “);
pw.println(“World”);
pw.format(“My least favourite device is %s and its price is $%d”,
“iPhone”, 100000);
pw.print – Outputs a String
pw.println – Outputs a String with a new line
pw.format – Outputs a String, and allows for format specifiers
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 46 / 67
File Output – Errors
catch (IOException e) {
e.printStackTrace();
}
catch – Acts as a safeguard to potential errors, prints an error message if
anything goes wrong; more on Exceptions later
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 47 / 67
File Output – Libraries
1 import java.io.FileWriter;
2 import java.io.PrintWriter;
3 import java.io.IOException;
All the classes that make file output possible
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 48 / 67
Assess Yourself
What does the following program write to the file?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 49 / 67
Assess Yourself
1 import java.io.PrintWriter;
2 import java.io.IOException;
3 import java.util.Random;
4
5 public class FileWrite2 {
6 public static void main(String[] args) {
7 final int MAX_NUM = 10000;
8 final int ITERATIONS = 1000000;
9
10 Random rand = new Random();
11
12 try (PrintWriter pw =
13 new PrintWriter(new FileWriter(“testOut2.txt”))) {
14
15 int nums[] = new int[MAX_NUM];
16
17 for (int i = 0; i < ITERATIONS; i++) {
18 nums[rand.nextInt(MAX_NUM)] += 1;
19 }
20 for (int i = 0; i < nums.length; i++) {
21 pw.format("%4d: %4d\n", i, nums[i]);
22 }
23 } catch (IOException e) {
24 e.printStackTrace();
25 }
26 }
27 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 50 / 67
Assess Yourself
What does the following program write to the file?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 51 / 67
Assess Yourself
1 import java.io.FileWriter;
2 import java.io.PrintWriter;
3 import java.io.IOException;
4 import java.util.Scanner;
5
6 public class FileWrite3 {
7 public static void main(String[] args) {
8
9 Scanner scanner = new Scanner(System.in);
10
11 try (PrintWriter pw =
12 new PrintWriter(new FileWriter("test.html"))) {
13
14 pw.println("
The Chronicles of SWEN20003
“);
15
16 while (scanner.hasNext()) {
17 String text = scanner.nextLine();
18
19 pw.println(“
” + text + “
“);
20 }
21
22 } catch (IOException e) {
23 e.printStackTrace();
24 }
25 }
26 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 52 / 67
File Input and Output
You will not be expected to write all of this from memory in the test/exam
If you are asked to manipulate files, you will be given sufficient
scaffold/supporting methods
For now, all you need to do is practice and understand; we’ll talk about
assessment closer to the test
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 53 / 67
Assess Yourself
Implement a rudimentary survey/voting system, by writing a program that continuously expects a single input
from the user. This input will be one of three options, in response to the question “Which is your favourite
Star Wars trilogy?”
The valid responses are 0 (for the “Original” trilogy), 1 (“New”), and 2 (“The other one”).
Once the input has ended, your program should output the results of the survey, one option per line, as below.
Execution:
0
0
1
1
1
2
Original Trilogy: 2
New Trilogy: 3
Other Trilogy: 1
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 54 / 67
Assess Yourself
1 import java.util.Scanner;
2
3 public class Survey1 {
4 public static void main(String[] args) {
5
6 final int N_OPTIONS = 3;
7
8 final int ORIGINAL = 0;
9 final int NEW = 1;
10 final int OTHER = 2;
11
12 int results[] = new int[N_OPTIONS];
13
14 Scanner scanner = new Scanner(System.in);
15
16 while (scanner.hasNextInt()) {
17 int vote = scanner.nextInt();
18 results[vote] += 1;
19 }
20
21 System.out.println(“Original Trilogy: ” + results[ORIGINAL]);
22 System.out.println(“New Trilogy: ” + results[NEW]);
23 System.out.println(“Other Trilogy: ” + results[OTHER]);
24
25 }
26 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 55 / 67
Assess Yourself
Follow up:
What would you do if there were five valid inputs?
What about n inputs?
What about allowing the user to tell you the options, then getting votes?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 56 / 67
Assess Yourself
Follow up:
What would you do if there were five valid inputs?
What about n inputs?
What about allowing the user to tell you the options, then getting votes?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 56 / 67
Assess Yourself
Follow up:
What would you do if there were five valid inputs?
What about n inputs?
What about allowing the user to tell you the options, then getting votes?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 56 / 67
Combining Reading and Writing
1 import java.io.FileReader;
2 import java.io.BufferedReader;
3 import java.io.FileWriter;
4 import java.io.PrintWriter;
5
6 public class FileReadWrite {
7 public static void main(String[] args) {
8
9 try (BufferedReader br = new BufferedReader(new FileReader(“input.txt”));
10 PrintWriter pw = new PrintWriter(new FileWriter(“output.txt”))) {
11
12 String text;
13
14 while ((text = br.readLine()) != null) {
15 pw.println(text.toLowerCase());
16 }
17 } catch (Exception e) {
18 e.printStackTrace();
19 }
20 }
21 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 57 / 67
Application #1: Data Storage/Retrieval
1 /** Using files to store intermediate data during computation */
2
3 final int MAX_DATA = 1000;
4
5 try (BufferedReader br = new BufferedReader(new FileReader(“input.txt”));
6 PrintWriter pw = new PrintWriter(new FileWriter(“output.txt”, true))) {
7
8 // Recover data from previous run
9 String oldData[] = loadPreviousData(br);
10
11 String newData[] = new String[MAX_DATA];
12
13 int count = 0;
14
15 while (magicalComputationNeedsDoing()) {
16 newData[count] = magicalComputation(oldData);
17
18 count += 1;
19
20 // Once we do enough computation, store the results just in case
21 if (count == MAX_DATA) {
22 writeData(pr, newData);
23 count = 0;
24 }
25 }
26
27 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 58 / 67
Application #2: Data Manipulation
1 /** Using Java to parse/manipulate/convert/etc. files */
2
3 try (BufferedReader br = new BufferedReader(new FileReader(“input.txt”));
4 PrintWriter pw = new PrintWriter(new FileWriter(“output.txt”))) {
5
6 String text;
7
8 while ((text = br.readLine()) != null) {
9 // Manipulate the input file
10 String newText = magicalComputation(text);
11
12 // Write to output file
13 pw.println(newText);
14 }
15
16 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 59 / 67
Assess Yourself
1 Write a program that accepts a filename from the user, which holds the
marks for students in SWEN20003. Your program must then process this
data, and output a histogram of the results
2 Extend your program so that it accepts two more inputs for the min and max
values for the data
3 Extend your program so that it accepts one more input for the width of each
“bin” in the histogram
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 60 / 67
Assess Yourself
1 Write a program that accepts a filename from the user, which holds the
marks for students in SWEN20003. Your program must then process this
data, and output a histogram of the results
2 Extend your program so that it accepts two more inputs for the min and max
values for the data
3 Extend your program so that it accepts one more input for the width of each
“bin” in the histogram
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 60 / 67
Assess Yourself
1 Write a program that accepts a filename from the user, which holds the
marks for students in SWEN20003. Your program must then process this
data, and output a histogram of the results
2 Extend your program so that it accepts two more inputs for the min and max
values for the data
3 Extend your program so that it accepts one more input for the width of each
“bin” in the histogram
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 60 / 67
Assess Yourself
1 import java.util.Scanner;
2 import java.io.File;
3
4 public class MarkHist {
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print(“Enter filename: “);
8 String filename = scanner.nextLine();
9
10 System.out.print(“Enter min value: “);
11 int min = scanner.nextInt();
12 scanner.nextLine();
13
14 System.out.print(“Enter max value: “);
15 int max = scanner.nextInt();
16 scanner.nextLine();
17
18 System.out.print(“Enter bin width: “);
19 int width = scanner.nextInt();
20 scanner.nextLine();
21
22 int data[] = new int[max-min + 1];
23
24 int total = 0;
25
26 …
27
28 }
29 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 61 / 67
Assess Yourself
1 try (Scanner file = new Scanner(new File(filename))) {
2 // Skip the first line
3 file.nextLine();
4
5 while (file.hasNext()) {
6 String line[] = file.nextLine().split(“,”);
7
8 int d = Integer.parseInt(line[1]);
9
10 data[d – min] += 1;
11 total += 1;
12 }
13
14 …
15
16 } catch (Exception e) {
17 e.printStackTrace();
18 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 62 / 67
Assess Yourself
1 // Print out graph
2 for (int i = 0; i < data.length; i += width) {
3 int sum = 0;
4
5 // Bundle into *width* sized blocks
6 for (int j = 0; j < width && i + j < data.length; j++) {
7 sum += data[i+j];
8 }
9
10 int percentage = (int) (100 * (1.0 * sum)/total);
11 String bar = "";
12
13 if (percentage > 0) {
14 bar = String.format(“%” + percentage + “s”, ” “)
15 .replace(” “, “=”);
16 }
17
18 int lower = i + min;
19 int upper = lower + width – 1;
20
21 // Print the block
22 System.out.format(“%03d-%03d: %s\n”, lower, upper, bar);
23 }
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 63 / 67
Assess Yourself
Write a program that takes three inputs from the user:
String, a unit of measurement
int, the number of units
String, an ingredient in a recipe
Your code should write in the following format to a file called “recipe.txt”:
“- Add 300 grams of chicken”
Bonus Task:
Open the file in “append” mode; this means the file will be added to, rather than
overwritten, each time you run your code.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 64 / 67
Assess Yourself
Write a program that takes three inputs from the user:
String, a unit of measurement
int, the number of units
String, an ingredient in a recipe
Your code should write in the following format to a file called “recipe.txt”:
“- Add 300 grams of chicken”
Bonus Task:
Open the file in “append” mode; this means the file will be added to, rather than
overwritten, each time you run your code.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 64 / 67
Assess Yourself
Write a program that accepts a filename from the user, and then processes that
file, recording the frequency with which words of different lengths appear.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 65 / 67
Assess Yourself
Write a program that accepts a HTML filename from the user, and then takes
continuous user input and writes it to the file; essentially a Java based HTML
writer.
Bonus #1: add validation to detect valid HTML tags (
,
, etc.).
Bonus #2: add “shortcuts”; for example, entering {text} might make text
automatically bold.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 66 / 67
Assess Yourself
Write a program that accepts a HTML filename from the user, and then takes
continuous user input and writes it to the file; essentially a Java based HTML
writer.
Bonus #1: add validation to detect valid HTML tags (
,
, etc.).
Bonus #2: add “shortcuts”; for example, entering {text} might make text
automatically bold.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 66 / 67
Assess Yourself
Write a program that accepts a HTML filename from the user, and then takes
continuous user input and writes it to the file; essentially a Java based HTML
writer.
Bonus #1: add validation to detect valid HTML tags (
,
, etc.).
Bonus #2: add “shortcuts”; for example, entering {text} might make text
automatically bold.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 66 / 67
Lecture Objectives
Upon completion of this topic you will be able to:
Accept input to your programs through:
I Command line arguments
I User input
I Files
Write output from your programs through:
I Standard output (terminal)
I Files
Use files to store and retrieve data during program execution
Manipulate data in files (i.e. for computation)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 67 / 67