【问题标题】:Modify class to write exceptions to text file修改类以将异常写入文本文件
【发布时间】:2015-05-18 01:25:40
【问题描述】:

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

修改 ProductMainApp 类,使其在 ProductTextFile 类中的 addProduct 和 deleteProduct mwthod 返回 flase 值时做出适当的响应。

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

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

这里是打印文本文件:

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

【问题讨论】:

    标签: java exception printwriter


    【解决方案1】:

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

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

    【讨论】:

    • 我从没想过使用它。放在哪里最好?
    • 这取决于您的应用程序的类型。如果它是一个独立的程序,那么可能在同一个目录中是好的,如果是一个 Web 应用程序,那么在 App 服务器的日志目录中会很好。
    • 尝试使用 log4j ,而不是你自己的方式。首先它会很快,然后它会更灵活。
    • @FengLin 如果这不是一次性程序,我同意。
    • 很抱歉,这一切都超出了我的想象。这是 Murach Java 书中的一个独立程序。它告诉我只修改程序中的 ProductMainApp 和 ProductTextFile。这就是我在问题中添加的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2012-01-27
    • 2012-08-16
    相关资源
    最近更新 更多