Output Processing PrintStream System.out Files Output Files - - PowerPoint PPT Presentation

output processing
SMART_READER_LITE
LIVE PREVIEW

Output Processing PrintStream System.out Files Output Files - - PowerPoint PPT Presentation

Output Processing PrintStream System.out Files Output Files PrintStream Class System.out is a PrintStream! We generally use it to output to the console: System.out.println( Hello W orld!) ; System.out.print (E nter name:


slide-1
SLIDE 1

Output Processing

PrintStream

  • System.out
  • Files

Output Files

slide-2
SLIDE 2

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.

slide-3
SLIDE 3
  • 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"));

  • utput.println("ant");
  • utput.print("bag");
  • utput.println("bug");}

}

PrintStream Class (cont.)

slide-4
SLIDE 4

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

slide-5
SLIDE 5
  • 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 must

still handle the FileNotFoundException! –throws clause –try/catch block

Output Files (cont.)

slide-6
SLIDE 6

import java.util.*; import java.io.*; public class JingleWriter { public static void main(String[] args) { try { File file = new File("jingle.txt"); PrintStream output = new PrintStream(file);

  • utput.println("My bologna has a first name It's O-s-c-a-r");
  • utput.println("My bologna has a second name It's M-a-y-e-r");
  • utput.println("Oh, I love to eat it everyday");
  • utput.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

slide-7
SLIDE 7

/** * 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 {

  • utput = new PrintStream(new File(name));

} catch (FileNotFoundException e) { System.out.println("File unable to be written. Please try again."); } } return output; }

getOutputPrintStream

slide-8
SLIDE 8

PrintStream output = null; while (output == null) { System.out.print("Enter output file name: "); File file = new File(console.next()); try { if (!file.exists()) {

  • utput = 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")) {

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

slide-9
SLIDE 9

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

  • utput.println(input.nextLine().toUpperCase());

} input.close(); // Close the Scanner

  • utput.close(); // Close the PrintStream

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

Read and Write

slide-10
SLIDE 10

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 {

  • utput = new PrintStream(file);

} catch (FileNotFoundException e) { System.out.println("hamletCaps.txt unable to be written: "+ e); System.exit(1); } while(input.hasNextLine()) {

  • utput.println(input.nextLine().toUpperCase());

} input.close(); // Close the Scanner

  • utput.close(); // Close the PrintStream

} }

slide-11
SLIDE 11

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

slide-12
SLIDE 12

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

slide-13
SLIDE 13
  • We can “redirect” System.out to a file:

$ java HelloWorld > output.txt

  • We can “redirect” both System.in and System.out

to files!

$ java CalculateGrade < testInput.txt > output.txt

Console Redirection

slide-14
SLIDE 14

Mixing tokens and lines

  • Using nextLine in conjunction with the

token-based methods on the same Scanner can 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?

slide-15
SLIDE 15

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 ^

slide-16
SLIDE 16

Line-and-token example

Scanner 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

^

slide-17
SLIDE 17

Line-and-token example

Scanner 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.

slide-18
SLIDE 18

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

slide-19
SLIDE 19

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: no 01/02/2010 Low: 24.1 High: 48.0 Rain: no Snow: no ... 12/26/2010 Low: 28.4 High: 36.0 Rain: yes Snow: yes 12/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

slide-20
SLIDE 20

YYYYMMDD Average(F) High(F) Low(F) Fog/Rain/Snow/Hail/Thunder/Tornado 20100101 44.2 48 34 100000 20100102 29.9 48 24.1 000000 20100103 24.2 32 18 000000 20100104 26.2 36 17.1 000000 20100105 26.9 36 17.1 000000 20100106 29.1 41 18 000000 20100107 32.4 48 19 000000 20100108 35.1 48 20.1 010000 20100109 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

slide-21
SLIDE 21

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

  • utput 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 spaces into 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 as follows: many spaces on this line! Hint: Use a line-based approach (create a line Scanner in collapseSpaces).