0

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");
}
}
}

1 Answers1

0

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)

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • I never thought about using that. Where would be the best place to put it? – Laura Bullard Mar 16 '15 at 01:23
  • That's depends on the type of your application. if it is a standalone program then maybe in the same directory is good, if a web application, then in the App servers log directory would be good. – Scary Wombat Mar 16 '15 at 01:25
  • Try use the log4j , instead of your own way. Firstly it will fast, then it will more flexible. – Feng Lin Mar 16 '15 at 01:25
  • @FengLin I agree if this is not a throw-away program. – Scary Wombat Mar 16 '15 at 01:27
  • I'm sorry this is all above my head. This is a stand alone program from Murach Java book. It tells me to modify only the ProductMainApp and ProductTextFile from the program. That is what I added in my question. – Laura Bullard Mar 16 '15 at 01:29
  • Ah ha, a quick search for `Java log Exception to file` returns this http://stackoverflow.com/questions/9362574/how-to-write-error-log-or-exception-into-file-in-java – Scary Wombat Mar 16 '15 at 01:49
  • I don't think that I am supposed to be using log4j yet. We have not learned about it yet. – Laura Bullard Mar 16 '15 at 01:53