从文本文件中读取数据并打印到文本文件Java

时间:2012-05-23 09:43:19

标签: java text-files

好的,输入文本文件格式如下:

product     sugar  
boughton    13-3-2012 
useby       12-12-2012 
boughtat    $3.56 
quantity    5 

product     sauce pan  
quantity    10 
boughtat    $19.99 
boughton    13-3-2012

product     sugar  
boughton    23-3-2012 
quantity    15
boughtat    $2.99 
useby       1-10-2012 

product     plate  
quantity    10 
boughtat    $-19.99 
boughton    13-3-2012

product     orange juice  
boughton    33-3-2012 
quantity    15
boughtat    $2.99 
useby       1-10-2012

我的代码: DataIn.java

class DataIn {

    public static ArrayList<Product> getData(String filename) {
        ArrayList<Product> recordlist = new ArrayList<Product>();
        int index = -1;
        try {
            File inFile = new File(filename);
            Scanner reader = new Scanner(inFile);
            String s;
            Product p = null;

            while (reader.hasNext()) {
                s = reader.nextLine();
                Scanner line = new Scanner(s);
                String cmd;
                if (line.hasNext()) {
                    cmd = line.next();
                    if (cmd.equalsIgnoreCase("product")) {
                        index++;
                        p = new Product();
                        p.setName(line.nextLine());
                        recordlist.add(index, p);
                    } else if (cmd.equalsIgnoreCase("boughton")) {
                        Calendar d;
                        d = ConvertToCal(line.nextLine());
                        p.setBoughtOn(d);
                        recordlist.set(index, p);
                    } else if (cmd.equalsIgnoreCase("useby")) {
                        Calendar d;
                        d = ConvertToCal(line.nextLine());
                        p.setUseBy(d);
                        recordlist.set(index, p);

                    } else if (cmd.equalsIgnoreCase("boughtat")) {
                        if (line.hasNextDouble()) {
                            p.setBoughtAt(line.nextDouble());
                            recordlist.set(index, p);
                        }
                    } else if (cmd.equalsIgnoreCase("quantity")) {
                        if (line.hasNextInt()) {
                            p.setQuantity(line.nextInt());
                            recordlist.set(index, p);
                        }
                    } else {
                        System.out.println("Error: no command");
                    }
                }
            }

            reader.close();


            return recordlist;
        } catch (Exception e) {
            System.out.println("Error" + e.getMessage());
            return null;
        }
    }

    public static Calendar ConvertToCal(String s) {
        try {
            Date d;
            DateFormat f = new SimpleDateFormat("dd-MM-yyyy");
            d = (Date) f.parse(s);

            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            return cal;
        } catch (ParseException e) {
            System.out.println("Exception: " + e);

        }
        return null;
    }

    // method to print the output in the file
    public static void writeData(ArrayList<Product> productlist, String fileName) {



        if (productlist.size() == 0) {
            System.out.println(" no product");
            return;

        }

        try {
            File fileOut = new File(fileName);
            PrintWriter out = new PrintWriter(fileOut);
            for (Product p : productlist) {
                out.println("product " + p.getName());
                out.println("boughtOn " + (p.getBoughtOn().get(Calendar.DATE)));
                out.println("useBy " + (p.getUseBy()).get(Calendar.DATE));  //ERROR in here
                out.println("boughtAt " + p.getBoughtAt());
                out.println("quantity " + p.getQuantity());
            }

            out.close();
        } catch (FileNotFoundException e) {
            System.out.println("file not found");
        }

    }
}

Product.java

//products class 
public class Product {
    private String name;
    private Calendar boughtOn;
    private Calendar useBy;
    private double boughtAt;
    private int quantity;
  // first product class constructor
  public Product (){
    name=null;
    boughtOn=null;
    useBy=null; 
    boughtAt=0;
    quantity=0;
 }
  //second product class constructor
  public Product( String pName, Calendar bOn, Calendar uBy, double bAt, int qt){
    name= pName;
    boughtOn=bOn;
    useBy=uBy;
    boughtAt= bAt;
    quantity=qt;
 }
  //method to get the name of product
   public String getName(){
      return name;
 }
 //method to get the date that product bought on
   public Calendar getBoughtOn() {
    return boughtOn;
}
  //method to get the date that product use by
 public Calendar getUseBy() {
  return useBy;
}
//method to get the purchase price of product
   public double getBoughtAt() {
      return boughtAt;
}
  //method to get the quantity of the product
   public int getQuantity() {
     return quantity;
   }
  //method to change the product name
 public  void setName (String n) {
 name=n;
}

  //method to change the date  that product bought on
 public void setBoughtOn( Calendar bo)   {
      boughtOn=bo;



}
 //method to set the date that product will expired at
    public void setUseBy( Calendar ub) {
    useBy=ub;
}
  //method to set the purchase price of product
  public void setBoughtAt( double ba) {
    boughtAt= ba;
 }
 //method to set the product quantity
   public  void setQuantity( int q) {
    quantity=q;
}
   public String toString (){
       return name +"\t" + boughtOn + "\t" + useBy + "\t" + boughtAt +"\t" + quantity;
   }
   public static void main(String []args){

        ArrayList<Product> list;
        list=DataIn.getData("products_1.txt");
        DataIn.writeData(list,"save1.txt");
}       

}

错误线程“main”中的异常java.lang.NullPointerException

在这行out.println(“useBy”+(p.getUseBy())。get(Calendar.DATE));在DataIn.java中

我想不通所以我在这里发帖全部,Mod请在java代码中重新格式化代码,我不知道该怎么做

此外,当我通过使用//避免该行时,程序可以运行,但我的输出文件只显示(买了和买了有问题)

product     sugar  
boughtOn 13
boughtAt 0.0
quantity 5
product     sauce pan  
boughtOn 13
boughtAt 0.0
quantity 10
product     sugar  
boughtOn 23
boughtAt 0.0
quantity 15
product     plate  
boughtOn 13
boughtAt 0.0
quantity 10
product     orange juice  
boughtOn 2
boughtAt 0.0
quantity 15

很抱歉,如果代码太长但很难解释我的问题。

1 个答案:

答案 0 :(得分:0)

输入列表中的某些产品缺少“useby”字段,因此您的错误是正常的,因为您的某些Product对象具有NULL useby字段。