Skip to content

Instantly share code, notes, and snippets.

@tarunbod
Created March 12, 2021 17:33
Show Gist options
  • Save tarunbod/61bfc9aaf6c359ae3dbeebd07209d53f to your computer and use it in GitHub Desktop.
Save tarunbod/61bfc9aaf6c359ae3dbeebd07209d53f to your computer and use it in GitHub Desktop.
Import and Export with txt files
public class Controller {
/**
Controller method that is called when the user clicks "Import From File"
on the fourth tab in the application. This method asks the user to select
a text file that contains account database information, reads the file,
and populates the account database with the accounts found in the file.
Prints errors if the file could not be read or if it was in a bad format.
@param event the ActionEvent generated by the button press. Ignored for
our purposes.
*/
@FXML
void onImportClicked(ActionEvent event) {
FileChooser chooser = new FileChooser();
chooser.setTitle("Import Database File");
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("Text files (*.txt)",
"*.txt");
chooser.getExtensionFilters().add(extFilter);
File importFile = chooser.showOpenDialog(null);
if (importFile == null) {
println("No file selected to import.");
return;
}
try {
Scanner sc = new Scanner(importFile);
sc.useDelimiter("[,\n]");
int numImported = 0;
while (sc.hasNext()) {
String accountType = sc.next();
String firstName = sc.next();
String lastName = sc.next();
Profile newProfile = new Profile(firstName, lastName);
double balance = sc.nextDouble();
String dateStr = sc.next();
String[] dateParts = dateStr.split("/");
int month = Integer.parseInt(dateParts[0]);
int day = Integer.parseInt(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);
Date newDate = new Date(year, month, day);
if (!newDate.isValid()) {
println("Invalid date encountered during import: "
+ dateStr + "; Ignoring.");
sc.nextLine();
continue;
}
String extraInfo = sc.next();
Account account;
if (accountType.equals("C")) {
boolean directDeposit = Boolean.parseBoolean(extraInfo);
account = new Checking(newProfile, balance, newDate,
directDeposit);
} else if (accountType.equals("S")) {
boolean loyalCustomer = Boolean.parseBoolean(extraInfo);
account = new Savings(newProfile, balance, newDate,
loyalCustomer);
} else if (accountType.equals("M")) {
int withdrawals = Integer.parseInt(extraInfo);
account = new MoneyMarket(newProfile, balance, newDate,
withdrawals);
} else {
println("Unknown account type '" + accountType + "'; " +
"Ignoring.");
continue;
}
if (database.add(account)) {
numImported++;
} else {
println(String.format(
"Ignoring %s; Account already exists in database.",
account.toString()
));
}
}
sc.close();
println(numImported + " accounts were imported from file.");
} catch (FileNotFoundException e) {
println("Selected file no longer exists.");
} catch (InputMismatchException | NumberFormatException e) {
println("Selected file has improper format.");
}
}
/**
Controller method that is called when the user clicks "Export To File"
on the fourth tab in the application. This method asks the user to select
a file to save the account database to, opens the file, and writes to it
the CSV-serialized form of the account database. Prints errors if the
file could not be written to.
@param event the ActionEvent generated by the button press. Ignored for
our purposes.
*/
@FXML
void onExportClicked(ActionEvent event) {
FileChooser chooser = new FileChooser();
chooser.setTitle("Export Account Database");
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("Text files (*.txt)",
"*.txt");
chooser.getExtensionFilters().add(extFilter);
chooser.setInitialFileName("database.txt");
File exportFile = chooser.showSaveDialog(null);
if (exportFile == null) {
println("No file selected to export to.");
return;
}
try {
BufferedWriter writer =
new BufferedWriter(new FileWriter(exportFile));
String output = database.exportAccounts();
writer.write(output);
writer.close();
} catch (IOException e) {
println("Error opening file for output.");
return;
}
println("Successfully exported to " + exportFile.getName());
}
}
public class Database {
public String exportAccounts() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < size; i++) {
Account account = accounts[i];
if (account instanceof Savings) {
str.append("S");
} else if (account instanceof Checking) {
str.append("C");
} else {
str.append("M");
}
str.append(",");
str.append(account.getHolder().getFname()).append(",");
str.append(account.getHolder().getLname()).append(",");
str.append(account.getBalance()).append(",");
str.append(account.getDateOpen().toString()).append(",");
if (account instanceof Savings) {
str.append(((Savings)account).isLoyal());
} else if (account instanceof Checking) {
str.append(((Checking)account).isDirectDeposit());
} else {
str.append(((MoneyMarket)account).getWithdrawals());
}
str.append("\n");
}
return str.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment