import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; /* * Same as the input one and the string vs int one, but now writting to a file * instead of the screen. */ public class mainProgram { public static ArrayList readInput(final String fileName) throws IOException{ FileInputStream fileByteStream = null; // File input stream Scanner scnr = null; // Scanner object System.out.println("Opening file " + fileName); fileByteStream = new FileInputStream(fileName); scnr = new Scanner(fileByteStream); String s = ""; String name; int age; ArrayList results = new ArrayList(); while(true){ //Get name or exit s = scnr.next(); if (s.equals("-1")){ System.out.println(); break; } else{ name = s; } //Get age try{ age = scnr.nextInt() +1; } catch(Exception e){ System.out.println("Age must be an Integer\n" + "Setting age to 0 "); age = 0; } //Finish line scnr.nextLine(); //Add name plus new age to arr results.add(name + " " + Integer.toString(age)); System.out.println(); } System.out.println("Closing scanner:"); fileByteStream.close(); scnr.close(); return results; } public static void writeArrayListToFile(ArrayList arr, final String fileName) throws IOException{ FileOutputStream fileStream = null; PrintWriter file = null; fileStream = new FileOutputStream(fileName); file = new PrintWriter(fileStream); System.out.println("Writing out results " + "To " + fileName ); for (String S:arr){ file.println(S); } file.flush(); fileStream.close(); file.close(); } public static void main(String[] args) throws IOException{ final String INPUTFILENAME = "NamesAndAges.txt"; final String OUTPUTFILENAME = "NamesAndAgesUpdated.txt"; ArrayList userInputs; //Get input userInputs = readInput(INPUTFILENAME); //Write to file writeArrayListToFile(userInputs, OUTPUTFILENAME); } }