101 lines
2.1 KiB
Java
Raw Normal View History

2021-03-10 16:07:13 -05:00
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.
*/
2021-03-11 11:24:36 -05:00
public class mainProgram {
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
public static ArrayList<String> 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);
2021-03-10 16:07:13 -05:00
String s = "";
String name;
int age;
ArrayList<String> results = new ArrayList<String>();
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();
}
2021-03-11 11:24:36 -05:00
System.out.println("Closing scanner:");
fileByteStream.close();
scnr.close();
2021-03-10 16:07:13 -05:00
return results;
}
2021-03-11 11:24:36 -05:00
public static void writeArrayListToFile(ArrayList<String> arr,
final String fileName)
throws IOException{
FileOutputStream fileStream = null;
PrintWriter file = null;
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
fileStream = new FileOutputStream(fileName);
file = new PrintWriter(fileStream);
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
System.out.println("Writing out results " +
"To " + fileName );
for (String S:arr){
file.println(S);
}
file.flush();
fileStream.close();
file.close();
}
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
public static void main(String[] args) throws IOException{
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
final String INPUTFILENAME = "NamesAndAges.txt";
final String OUTPUTFILENAME = "NamesAndAgesUpdated.txt";
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
ArrayList<String> userInputs;
2021-03-10 16:07:13 -05:00
2021-03-11 11:24:36 -05:00
//Get input
userInputs = readInput(INPUTFILENAME);
2021-03-10 16:07:13 -05:00
//Write to file
2021-03-11 11:24:36 -05:00
writeArrayListToFile(userInputs, OUTPUTFILENAME);
2021-03-10 16:07:13 -05:00
}
}