Question: Look at the following method. Right now it does not even compile. How would you fix it? Keep these thoughts in mind. If a programmer
Look at the following method. Right now it does not even compile. How would you fix it? Keep these thoughts in mind.
- If a programmer calls the method, and the method cannot create the output file, the method should notify the caller that a problem occurred. Look at the PrintWriter constructor to see how it handles this situation.
- If an error occurs when writing to the file, you'll need to make sure that all of the data you've written so far has been safely saved.
________________________________________
LineWriter.java
import java.io.FileNotFoundException; import java.io.PrintWriter;
public class LineWriter { public static void writeAll(String[] lines, String filename) { PrintWriter out = new PrintWriter(filename); for (String line : lines) { out.println(line.toUpperCase()); } out.close(); } }
__________________________________
LineWriterTester.java
import java.util.*;
import java.io.*;
import java.nio.file.*;
public class LineWriterTester { public static void main(String[] args) {
// This tests that the method throws a FileNotFoundException
String[] array = {"mary", "had", "a", "little", "lamb"};
try {
LineWriter.writeAll(array, "nodir/nofile.txt");
System.out.println("Should have throw an exeption, but did not."); }
catch (Throwable e) { if (e.getClass().getSimpleName().equals("FileNotFoundException")) System.out.println("FileNotFoundException thrown"); else System.out.println("Throws " + e.getClass().getSimpleName()); } System.out.println("Expected: FileNotFoundException thrown ");
try{ LineWriter.writeAll(array, "output.txt"); System.out.println("Throws no exceptions"); } catch (Exception e) { System.out.println("Throws " + e.getClass().getSimpleName() + ", but should not"); } System.out.println("Expected: Throws no exceptions "); // This version tests to see what happens when the input String contains a null. array = new String[] {"mary", "had", null, "little", "lamb"}; String[] copy = {"MARY", "HAD"}; try { LineWriter.writeAll(array, "output.txt"); // Should throw a NullPointerException. If it does not, we have a problem System.out.println("Should throw an exception."); } catch (Exception e) { if (e.getClass().getSimpleName().equals("NullPointerException")) { List lines = null; try { lines = Files.readAllLines(Paths.get("output.txt")); System.out.println("Actual: " + Arrays.toString(lines.toArray())); } catch (IOException ioe) { System.out.println("Actual: data not saved to file."); } } else { System.out.println("Throws " + e.getClass().getSimpleName() + ", but should not."); } } System.out.println("Expected: " + Arrays.toString(copy)); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
