import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** * Copies the contents of one file into another and prints the contents to the console. * @author Sarah Larkin * CS3090, Spring 2018 * Date Last Modified: March 7, 2017 * */ public class SimpleFileIO { public static void main(String[] args) { SimpleFileIO self = new SimpleFileIO(); String input = self.readFile("Stevenson.txt"); self.printFile(input, "StevensonCopy.txt"); System.out.println("Copying finished"); } /** * Reads in a file and returns its contents as a string * @param filename the name of the file to read in, including its type * @return the contents string */ public String readFile(String filename) { String input = ""; try(Scanner scan = new Scanner(new File(filename))) { while(scan.hasNext()) { input += scan.nextLine() + "\n"; } } catch (FileNotFoundException e) { e.printStackTrace(); } return input; } /** * Prints a string to the specified file and the console. * @param fileOutput the string to print * @param filename the file to which to print the string */ public void printFile(String fileOutput, String filename) { try(PrintWriter print = new PrintWriter(new File(filename))) { print.print(fileOutput); System.out.println(fileOutput); } catch (FileNotFoundException e) { e.printStackTrace(); } } }