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: ”) ; • All the methods you have used on System.out: print , println, printf will work on any PrintStream object.
PrintStream Class (cont.) • 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");} }
Output Files 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 (cont.) • 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
Error message if cannot create file 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); 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!" ); } } }
getOutputPrintStream /** * 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; }
How to handle do not overwrite and reprompt 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); } }
Read and Write 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); } } }
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 } }
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
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
Console Redirection • 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
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?
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\t 3.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\n Joe\t"Hello" world \n\t\t45.2 19\n ^
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\n S ideshow Bob ^
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.
TEAM EXERCISE - WeatherReporter 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
Recommend
More recommend