修改类以将异常写入文本文件

时间:2015-03-16 01:11:56

标签: java exception printwriter

我真的只需要为这段代码指明方向。我不明白如何完成它的要求。

修改ProductMainApp类,以便它在ProductTextFile类中的addProduct和deleteProduct mwthod返回flase值时适当地响应。

修改ProductTextFile类,使其将异常写入tex文件名errorLog.txt,而不是将它们打印到控制台。为此,添加一个名为printToLogFile的方法,该方法接受IOException作为参数。此方法应将两条记录附加到日志文件中:一条记录​​表示发生异常的日期和时间,另一条记录包含异常信息。

修改getProducts和saveProducts方法,以便在发生错误时调用printToLogFile方法。

这是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;
}

}

这是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 个答案:

答案 0 :(得分:0)

您可以使用Exception.printStackTrace (stream)其中stream是文件的输出流。

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)