printstream - nc state computer science · •in your exercises folder: git clone url •cd into...

21
Output Processing PrintStream System.out Files Output Files

Upload: others

Post on 30-Jan-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Output Processing

PrintStream

• System.out

• Files

Output Files

Page 2: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

PrintStream Class

• System.out is a PrintStream!

• We generally use it to output to the console:

System.out.println(“Hello World!”);

System.out.print(“Enter name: ”);

• All the methods you have used on

System.out: print, println, printf

will work on any PrintStream object.

Page 3: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

• We can use the PrintStream class to write to a file:

import java.util.*; import java.io.*;

public class PrintWords {public static void main(String [] args) throws FileNotFoundException {

PrintStream output = new PrintStream(new File("words.txt")); output.println("ant");output.print("bag"); output.println("bug");}

}

PrintStream Class (cont.)

Page 4: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

System.out.print("Enter filename for output data: "); String filename = console.next();PrintStream output = new PrintStream(new File(filename));

• If the file does not exist, a new file will be created.• If the file does exist, it will be overwritten!!!!

//Check with user if file exists! File file = new File(filename); if (file.exists()) {

System.out.print("OK to overwrite file? (y/n): ");

//if ‘y’ then create output PrintStream object

}

Output Files

Page 5: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

• When a PrintStream object is created a FileNotFoundException exception is generated if Java is unable to create the requested file

− no permission to write to directory− file might be locked by another program

• Whether or not the output file exists, we muststill handle the FileNotFoundException!

– throws clause

– try/catch block

Output Files (cont.)

Page 6: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

importjava.util.*; importjava.io.*;public class JingleWriter {

public static void main(String[] args) {try {

File file = new File("jingle.txt");PrintStream output = new PrintStream(file); output.println("My bologna has a first name It's O-s-c-a-r"); output.println("My bologna has a second name It's M-a-y-e-r"); output.println("Oh, I love to eat it everyday");output.println("Cuz Oscar Mayer has a way with B-o-l-o-g-n-a");

} catch (FileNotFoundException e) { System.out.println("Problem creating file!");

}}

}

Error message if cannot create file

Page 7: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

/**

* Returns a PrintStream for output to a file. NOTE: If file exists, this

* code will overwrite the existing file. It is likely that you want to add

* additional tests.

*

* @param console Scanner for console.

* @return PrintStream for output to a file

*/

public static PrintStream getOutputPrintStream(Scanner console) {

PrintStream output = null;

while (output == null) {

System.out.print("output file name? ");

String name = console.next();

try {

output = new PrintStream(new File(name));

} catch (FileNotFoundException e) {

System.out.println("File unable to be written. Please try again.");

}

}

return output;

}

getOutputPrintStream

Page 8: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

PrintStream output = null;while (output == null) {

System.out.print("Enter output file name: ");File file = new File(console.next());try {

if (!file.exists()) {output = new PrintStream (file);

} else {

System.out.print ("File already exists, do you want to overwrite it (y/n)?");String reply = console.next();if (reply.equals("y") || reply.equals("Y")) {

output = new PrintStream (file);}

}} catch (FileNotFoundException e) {

System.out.println(“File unable to be written: " + e);System.exit(1);

}}

How to handle do not overwrite and reprompt

Page 9: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

import java.util.*; import java.io.*;public class HamletCapitalize {

public static void main(String[] args) { try {

Scanner input = new Scanner(new File("hamlet.txt")); File file = new File("hamletCaps.txt");PrintStream output = new PrintStream(file); while(input.hasNextLine()) {

output.println(input.nextLine().toUpperCase());}input.close(); // Close the Scanner output.close(); // Close the PrintStream

} catch (FileNotFoundException e) { System.out.println("Error: "+ e);

}}

}

Read and Write

Page 10: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

import java.util.*; import java.io.*;public class HamletCapitalize {

public static void main(String[] args) { Scanner input = null;PrintStream output = null; try {

input = new Scanner(new File("hamlet.txt"));} catch (FileNotFoundException e) {

System.out.println("hamlet.txt does not exist."); System.exit(1);

}File file = new File("hamletCaps.txt"); try {

output = new PrintStream(file);} catch (FileNotFoundException e) {

System.out.println("hamletCaps.txt unable to be written: "+ e); System.exit(1);

}while(input.hasNextLine()) {

output.println(input.nextLine().toUpperCase());}input.close(); // Close the Scanner output.close(); // Close the PrintStream

}}

Page 11: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

In-class Exercise• Create (and submit to Moodle) a class

named HamletDouble that:

– Writes a double spaced version of the hamlet.txt file to a file named hamletDouble.txt

• Use the HamletCapitalize class as a template.

• Read in the hamlet.txt file line by line and

• Write each line to the output file

• Write a blank line to the output file after each line of text

Page 12: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

PrintStream Tips• Don’t declare a PrintStream object in a method that gets

called many times.

– This causes the file to be re-opened and wipes the past

contents. So only the last line shows up in the file.

• If a PrintStream object is tied to a file, then

– The output you print appears in a file, NOT on the

console window.

– You will have to open the file with an editor to view its

contents.

• Do not open the same file for both reading (Scanner)

and writing (PrintStream) at the same time.

– You will overwrite your input file with an

empty file (0 bytes).12

Page 13: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

• We can “redirect” System.out to a file:

$ java HelloWorld > output.txt

• We can “redirect” both System.in and System.outto files!

$ java CalculateGrade < testInput.txt > output.txt

Console Redirection

Page 14: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Mixing tokens and lines•Using nextLine in conjunction with the

token-based methods on the same Scannercan cause bad results.

23 3.14

Joe "Hello" world

45.2 19

– You'd think you could read 23 and 3.14 with nextInt and nextDouble, then read Joe "Hello" world with nextLine .

System.out.println(input.nextInt()); // 23

System.out.println(input.nextDouble()); // 3.14

System.out.println(input.nextLine()); //

– But the nextLine call produces no output! Why?

Page 15: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Mixing lines and tokens•When reading both tokens and lines from

the same Scanner: 23 3.14

Joe "Hello world"

45.2 19

input.nextInt() // 23

23\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n

^

input.nextDouble() // 3.14

23\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n

^

input.nextLine() // "" (empty!)

23\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n

^

input.nextLine() // "Joe\t\"Hello\" world"

23\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n

^

Page 16: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Line-and-token exampleScanner console = new Scanner(System.in);

System.out.print("Enter your age: ");

int age = console.nextInt();

System.out.print("Now enter your name: ");

String name = console.nextLine();

System.out.println(name + " is " + age + " years old.");

Log of execution (user input underlined):Enter your age: 12

Now enter your name: Sideshow Bob

is 12 years old.

•Why?– Overall input: 12\nSideshow Bob

– After nextInt(): 12\nSideshow Bob^

– After nextLine(): 12\nSideshow Bob

^

Page 17: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Line-and-token exampleScanner console = new Scanner(System.in);

System.out.print("Enter your age: ");

int age = console.nextInt();

//Add an extra console.nextLine() to read \n

console.nextLine();

System.out.print("Now enter your name: ");

String name = console.nextLine();

System.out.println(name + " is " + age + " years old.");

Log of execution (user input underlined):

Enter your age: 12

Now enter your name: Sideshow Bob

Sideshow Bob is 12 years old.

Page 18: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Will submit via github for this exercise.

• Go to ncsu github website and copy the url for Lab15 to clone

• In your Exercises folder: git clone url• cd into your CSC116-xxx-Lab15-yy folder• Download the RaleighWeather2010.txt into the repo

folder (right-click save link as)

One member of the team:

• Create the WeatherReporter.java file (see next 2 slides)• Push file to the repo:

• git add WeatherReporter.java• git commit –m “add WeatherReporter.java”• git push

Other team members:• git pull

TEAM EXERCISE - WeatherReporter

Page 19: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Write a program called WeatherReporter that:• prompts the user for an input file name (reprompt if file doesn’t exist) , • reads the given file, which is in the format of RaleighWeather2010.txt line by line

and uses the processLine() method as defined below to• output the data for each day to a file named "WeatherReporterOutput.txt".

public static void processLine(String line, PrintStream output) {

}

The output should be formatted as shown below:

01/01/2010 Low: 34.0 High: 48.0 Rain: no Snow: no01/02/2010 Low: 24.1 High: 48.0 Rain: no Snow: no... 12/26/2010 Low: 28.4 High: 36.0 Rain: yes Snow: yes12/27/2010 Low: 21.2 High: 37.4 Rain: no Snow: no...• You can assume the input file is formatted correctly and you don't have to check if

the output file exists (just overwrite it). • Use try/catch (not throws clause) when creating the input file Scanner and output

file PrintStream. • If a FileNotFoundException occurs when creating the output file

PrintStream, output an error message to the console and exit.

TEAM EXERCISE - WeatherReporter

Page 20: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

YYYYMMDD Average(F) High(F) Low(F) Fog/Rain/Snow/Hail/Thunder/Tornado20100101 44.2 48 34 10000020100102 29.9 48 24.1 00000020100103 24.2 32 18 00000020100104 26.2 36 17.1 00000020100105 26.9 36 17.1 00000020100106 29.1 41 18 00000020100107 32.4 48 19 00000020100108 35.1 48 20.1 01000020100109 25.9 35.6 19.4 000000

• Discard the first line (headers)• Read in date as a String – use substrings to output in correct format• Discard Average• Read in high and low as doubles• Read in weather as String, use index of Rain and Snow to determine if

1 (yes) or 0 (no)• Ignore all other weather types• Use a printf to format the output

TEAM EXERCISE - RaleighWeather2010.txt

Page 21: PrintStream - NC State Computer Science · •In your Exercises folder: git clone url •cd into your CSC116-xxx-Lab15-yy folder •Download the RaleighWeather2010.txt into the repo

Lab Exercise• Go to the moodle page and work on the OneSpace.java assignment.

In a class named OneSpace, write a main() method that:– Prompts the user for the names of an input file and an output file. – Creates a file Scanner for the input file and a PrintStream associated with the

output file (you don't need to check if the file exists). – Uses separate try/catch blocks for creating the Scanner and the PrintStream.– If a FileNotFoundException is caught, prints an appropriate error message and

exit with a System.exit(1);– Calls the collapseSpaces method (defined below).– Closes the input Scanner and output PrintStream.

Write a method named collapseSpaces that:– Accepts a Scanner representing an input file and a PrintStream representing

an output file as its parameters,– Reads each line of the input file and outputs it to the output file with all its

tokens separated by single spaces (collapsing any sequence of multiple spacesinto a single space).

For example, consider the following text:many spaces on this line!

If this text were a line in the input file, the same line should be written to the output file asfollows:many spaces on this line!

Hint: Use a line-based approach (create a line Scanner in collapseSpaces).