using a jframe i am trying to create a list of students, save them onto a file, re-read all those students and create new ones if, and only if, their id numbers are not the same. If the ID numbers are the same i am supposed to get an error message saying that that ID is already in use and thus not be able to register the new student. The only problem here is that even if the ID has already been used, it registers the students. What am i doing wrong?
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class NewEstudiantesJFrame extends javax.swing.JFrame {
public static List <Estudiantes> EstReg = new ArrayList<>();
public static Long ci, ciprueba;
public NewEstudiantesJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
private void AceptarButtonActionPerformed(java.awt.event.ActionEvent evt) {
Estudiantes estu = new Estudiantes();
try {
FileInputStream fis = new FileInputStream("t.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
EstReg = (List<Estudiantes>) ois.readObject();
ois.close();// es necesario cerrar el input stream
} catch (IOException | ClassNotFoundException ex) {
}
String NumId = new String();
String tipoId = (String) TipoIdBox.getSelectedItem();
estu.TipoId = tipoId;
NumId = NumIdField.getText();
if ((NumId.length()>9)||(NumId.length()<8)){
JOptionPane.showMessageDialog(null, "Please Type in the 8 or 9 ID digits");
a++;
NumIdField.setText(null);
//NumIdField.requestFocusInWindow();
}
else
{ ci = Long.parseLong(NumId);
}
try{
**for (Estudiantes e : EstReg){
if (e.NumId == Long.parseLong(NumId)){
JOptionPane.showMessageDialog(null, "ID already in use, please check your data");
NumIdField.setText(null);
NumIdField.requestFocusInWindow();
}
else {
estu.NumId = ci;
}**
}
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Inpult only ID numbers");
a++;
}
Here's my Estudiantes class
import java.io.Serializable;
public class Estudiantes implements Serializable{
String Nombre;
String Apellido;
String Direccion;
String Email;
String CursoActual;
String TipoId;
Long NumId;
String IdTotal;
String CodTel;
Long NumTel;
}
Thanks
Not sure if this will work but try using .compareTo() when comparing both of the longs instead of ==. Then check to see if the resulting value is equal zero.
https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html#compareTo-java.lang.Long-
Sorry my bad, i just realized i hadn't shown the rest of the code... Really sorry about that. I had to take a previous version of the same file and go with the .compareTo option. Thanks for the link Bryan Herrera.
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class NewEstudiantesJFrame extends javax.swing.JFrame {
public static List <Estudiantes> EstReg = new ArrayList<>();
public NewEstudiantesJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
private void AceptarButtonActionPerformed(java.awt.event.ActionEvent evt) {
Estudiantes estu = new Estudiantes();
try {
FileInputStream fis = new FileInputStream("C:\\t.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
EstReg = (List<Estudiantes>) ois.readObject();
ois.close();
} catch (IOException | ClassNotFoundException ex) {
}
String NumId = new String();
String nombre = new String();
String numTel = new String();
nombre = NombreField.getText();
String apellido = ApellidoField.getText();
String direccion = DireccionArea.getText();
String codtel;
boolean curso;
curso = false;
int a = 0;
String tipoId = (String) TipoIdBox.getSelectedItem();
estu.TipoId = tipoId;
if ((nombre.length()== 0)|| apellido.isEmpty()){
JOptionPane.showMessageDialog(null, "Please type in students full name");
a++;
}
else{
estu.Nombre = NombreField.getText();
estu.Apellido = ApellidoField.getText();
if (direccion.length()== 0){
JOptionPane.showMessageDialog(null, "Please input Student's address");
a++;
}
else{
estu.Direccion = DireccionArea.getText();}
}
try {
NumId = NumIdField.getText();
if ((NumId.length()!=8)){
JOptionPane.showMessageDialog(null, "Please type in the 8 digits if your ID");
a++;
NumIdField.setText(null);
else{
estu.NumId = Long.parseLong(NumId);
}
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Inpult only ID numbers");
a++;
}
for (Estudiantes es: EstReg){
if (es.NumId.compareTo(estu.NumId)==0){
JOptionPane.showMessageDialog(null,"ID already in use, please check your data");
NumIdField.setText(null);
a++;
}
}
try {
numTel = NumTelField.getText();
if (numTel.length()!=7){
JOptionPane.showMessageDialog(null, "Please type in the 7 telephone number digits");
a++;
}
else
estu.NumTel = Long.parseLong(numTel);
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Error. Only accepts numbers");
NumTelField.setText(null);
a++;
}
if (jRadioButton1.isSelected()){
estu.CursoActual= "Maths 1";
curso = true;
}
if (jRadioButton2.isSelected()){
estu.CursoActual ="Maths 2";
curso = true;
}
if (jRadioButton3.isSelected()){
estu.CursoActual ="Maths 3";
curso = true;
}
if ((curso == false) || (a > 0)){
JOptionPane.showMessageDialog(null, "Please finish filling the form out");
}
else{
ObjectOutputStream oos = null;
try {
JOptionPane.showMessageDialog(null, "Student succesfully registered. Thank you!");
estu.IdTotal = tipoId + NumId;
EstReg.add(estu);
FileOutputStream fos = new FileOutputStream("C:\\t.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(EstReg);
oos.close();
this.dispose();
} catch (Exception ex) {
}
}
}
Related
So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks
public class PasswordKeeper{
private ArrayList<SuperUser> users;
private static Scanner keyboard = new Scanner(System.in);
public PasswordKeeper() {
users = new ArrayList();
}
public void login() {
try {
// reads in SuperUser arraylist
get();
} catch (EOFException a) {
System.out.println("You are the First User!");
} catch (IOException b) {
System.out.println(b);
} catch (ClassNotFoundException c) {
System.out.println(c);
}
boolean loopDisplay = true;
while (loopDisplay) {
existingUser = keyboard.next();
existingPass = keyboard.next();
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
//saves after method call is over
try {
System.out.println("Saving.");
save(users);
} catch (IOException e) {
System.out.println(e);
}
}
}
//This happens if there is a new user
if(answer == 2){
SuperUser tempNew = null;
boolean cont = true;
String newUser;
String pass;
while(cont){
newUser = keyboard.nextLine();
System.out.println();
//System.out.println(users.size());
tempNew = new SuperUser(newUser, pass);
if(passValid(pass) == true){
if(makeSure(tempNew) == true){
System.out.println("Login Created!");
tempNew = new SuperUser(newUser, pass);
//actually being added to the arraylist
users.add(tempNew);
cont = false;
}
}
}
//SuperUser.display method
tempNew.display();
try{
System.out.println("Saving.");
save(users);
}catch(IOException e){
System.out.println(e);
}
}
}
}
//makeSure and passValid methods
public boolean makeSure(SuperUser user){
if(users.contains(user)){
return false;
}
return true;
}
public boolean passValid(String pass){
boolean passes = false;
String upper = "(.*[A-Z].*)";
String lower = "(.*[a-z].*)";
String numbers = "(.*[0-9].*)";
String special = "(.*[,~,!,#,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";
if((pass.length()>15) || (pass.length() < 8)){
System.out.println("Entry must contain over 8 characters\n" +
"and less than 15.");
passes = false;
}if(!pass.matches(upper) || !pass.matches(lower)){
System.out.println("Entry must contain at least one uppercase and lowercase");
passes = false;
}if(!pass.matches(numbers)){
System.out.println("Password should contain atleast one number.");
passes = false;
}if(!pass.matches(special)){
System.out.println("Password should contain atleast one special character");
passes = false;
}else{
passes = true;
}
return passes;
//serializable methods
public void save(ArrayList<SuperUser> obj) throws IOException {
File file = new File("userInformation.dat");
FileOutputStream fileOut = new FileOutputStream(file, false);
BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
out.writeObject(obj);
out.close();
fileOut.close();
}
public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("userInformation.dat");
BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
ObjectInputStream in = new ObjectInputStream(buffedInput);
users = (ArrayList<SuperUser>) in.readObject();
in.close();
fileIn.close();
return users;
}
public class SuperUser implements Serializable {
private String userName;
private String password;
private static Scanner keyboard = new Scanner(System.in);
private ArrayList<LoginInfo> info = new ArrayList();
public SuperUser(String name, String pass) {
userName = name;
password = pass;
}
public String getUser() {
return userName;
}
public void display() {
String next = keyboard.next();
//want to add data to LoginInfo arraylist
if (next.equalsIgnoreCase("add")) {
add();
} else if (next.equalsIgnoreCase("delete")) {
delete();
} else if (numberCheck(next)) {
int choice = (int) Integer.parseInt(next) - 1;
edit(choice);
//!!!! this: after doing this i lose whatever data i added
//to the LoginInfo arraylist, right after this the
//SuperUser arraylist gets saved. but the added data to
//loginInfo does not
} else if (next.equalsIgnoreCase("logout")) {
System.out.println(info.size());
}
}
public boolean numberCheck(String in) {
try {
Integer.parseInt(in);
} catch (NumberFormatException e) {
return false;
}
return true;
}
//method to add to the Arraylist
public void add() {
System.out.println("What is the website name?:");
String trash = keyboard.nextLine();
String webName = keyboard.nextLine();
System.out.println("The Username?:");
String webUsername = keyboard.nextLine();
System.out.println("The Password?:");
String webPass = keyboard.nextLine();
info.add(new LoginInfo(webUsername, webPass, webName));
System.out.println(info.size());
//method goes back to display
display();
}
}
}
Your problem is here
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
You create a temporary object which with the username and password.
Your 'users.contains()' method returns true because '.equals()' is based on the username, however the 'temp' object is a different instance to that in the list.
So when you call 'temp.display()' it is not calling on an object in the list, so no data changes will save.
You need to find the existing object from the list for that user. I would suggest that you swap your list for a map keyed on username.
You have a list named users. Once you created new SuperUser instance (temp), you are checking that it belongs to this list (users.contains(temp), which is false of course - from where it will occur there?). If it have belonged, the method display would be called, which in turn would add LoginInfo to that SuperUser (add() call), but I bet in reality it doesn't happened.
Also, I see where you read from users (check whether new SuperUser instances belong there), I see where you overwrite it (during desealization) but I don't see adding any instance to there, which makes me think that it is always empty.
Are you sure that SuperUser contains any LoginInfo in its array list?
I have read the file and it should print out the data on the console, but the problem is that I get this error message: Exception in thread "main" java.lang.NumberFormatException: For input string: "UNKNOWN". I've put the maximum length as an integer, but how do I put it as a string as well?
Here's what I have done so far:
import java.util.*;
import java.io.*;
public class Task1 {
public static void main(String[] args) {
List<Person> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("people-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] peopleData = fileRead.split(":");
String commonName = personData[0];
String latinName = personData[1];
int maximumLength = Integer.parseInt(personData[2]);
Person personObj = new Person(commonName, latinName, maximumLength);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
System.out.println(personFile);
}
}
Person Class:
import java.util.*;
public class Person1 {
private String commonName;
private String latinName;
private int maximumLength;
public Person1(String personName, String latinName, int maximumLength) {
this.commonName = personName;
this.latinName = latinName;
this.maximumLength = maximumLength;
}
public String getCommonName() {
return commonName;
}
public String getLatinName() {
return latinName;
}
public int getMaximumLength() {
return maximumLength;
}
#Override
public String toString() {
return null;
}
}
Text File:
Alisha Khan:Cephaloscyllium ventriosum:100
Jessica Lane:Galeocerdo cuvier:UNKNOWN
Michael Brown:Sphyrna mokarren:600
...
This line in your input file:
Jessica Lane:Galeocerdo cuvier:UNKNOWN
is causing problem on this line in your code:
int maximumLength = Integer.parseInt(personData[2]);
because parseInt throws NumberFormatException on UNKNOWN. You need to decide what you want to do in this case. For example this code will keep maximumLength to default value -1 when an invalid integer is encountered:
int maximumLength = -1;
try {
int maximumLength = Integer.parseInt(personData[2]);
} catch (NumberFormatException e) {
}
You should teach your code your convention of UNKNOWN. Currently the code treats it as number.
When I modify the instance variables RDBF and RIPF with the methods getIP() and cngDB() and than I sum them in the rsltUPDT() I do get the properties file i'm needing, but when I just need to modify one value of the two values inside the rsltUPDT() method and in prp.setProperty("db.connection", RIPF + RDBF); I can modify one value, but the other one gets setted to null.
How can I fix this?
import java.util.*;
import javax.swing.JOptionPane;
import java.io.*;
public class TztDB {
private static String RIPF;
private static String RDBF;
public void getNewFile() throws Exception {
Properties prp = new Properties();
File flix = new File("default.properties");
FileOutputStream fileu = new FileOutputStream(flix);
prp.setProperty("db.connection", "");
prp.store(fileu, "Si vez esto, el archivo se creo exitosamente");
fileu.close();
}
public String changeDB() {
Scanner c = new Scanner(System.in);
System.out.println("OK!. Especifique la base de datos: ");
RDBF = c.nextLine();
return RDBF;
}
public void getCKT() throws Exception {
TztDB tzt = new TztDB();
File f = new File("./default.properties");
if (f.exists() && !f.isDirectory()) {
System.out.println("Cargado");
} else {
JOptionPane.showMessageDialog(null, "Error. Archivo no encontrado o directorio incorreto. Creando archivo nuevo.", "Error de Aplicacion", JOptionPane.ERROR_MESSAGE);
tzt.getNewFile();
}
}
public String getIP() throws IOException, InputMismatchException {
Scanner scnIP = new Scanner(System.in);
System.out.println("Hola! Buena Eleccion.");
System.out.print("IP: ");
RIPF = scnIP.nextLine();
return RIPF;
}
public void getUserOP() {
TztDB obk = new TztDB();
Scanner input1 = new Scanner(System.in);
int OP;
System.out.print("Hola, Usuario! ¿Que deseas hacer? \n\n ");
System.out.println("1-Cambiar Direccion IP. \n 2-Cambiar Base de Datos. ");
try {
OP = input1.nextInt();
if (OP == 1) {
try {
obk.getIP();
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else if (OP ==2) {
try {
obk.changeDB();
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else if(OP == 3) {
System.out.println("404 :)!");
} else {
System.out.println("Opcion invalida. Reinice el programa...");
}
} catch (Exception x) {
System.out.println(x.getMessage());
}
}
public void rsltUPDT() throws Exception {
TztDB c = new TztDB();
Scanner CIN = new Scanner(System.in);
Properties prp = new Properties();
prp.setProperty("db.connection", RIPF + RDBF);
File flix = new File("default.properties");
FileOutputStream fileu = new FileOutputStream(flix);
prp.store(fileu, "Si vez esto, la operacion fue un exito!");
fileu.close();
}
public static void main(String [] args) throws Exception {
TztDB cole = new TztDB();
cole.getCKT();
cole.getUserOP();
cole.rsltUPDT();
}
}
DESCRIPTION:
In my program, users are asked to input some values. The values get stored into an ArrayList so that I can print them out. Now the problem with this one is all data is lost once I terminate the program. That's why I have decided to store those arrayList object into file and and read them from there.
PROBLEM/QUESTION:
I have created all the related methods to write and read file. But it seems that no objects are written and read in file.The class I am mainly concerned about is ReadWrite.
Working code:
ReadWrite:
public void writeFile(List<PersonInfo> information) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
AboutPerson:
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
rw.writeFile(info);
info2=rw.readFile();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
PersonInfo:
........
........
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
.........
.........
package com.collection;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class PersonInfo implements Serializable{
private String name;
private int id;
private double credit;
public PersonInfo(){}
public PersonInfo(String name,int id,int credit)
{
this.name=name;
this.id=id;
this.credit=credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
class ReadWrite
{
public void writeFile(List<PersonInfo> information){
try {
FileOutputStream fos = new FileOutputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
}
public class AboutPerson {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
int option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
rw.writeFile(info);
break;
case 2:
//display them
info2=rw.readFile();
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pinfo : info2) {
System.out.println(pinfo.getName()+"\t\t"+pinfo.getId()+"\t\t"+pinfo.getCredit());
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
}
}
Please implement serializable interface in PersonInf class.When u going to write object into file then u need to implement serializable interface other wise u will get exception like this:
java.io.NotSerializableException: com.collection.PersonInfo
first PersonInfo should implement SerialiZable,
and i'm not sure but PersonInfo should also have a default constructor
I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)