2014-10-19 77 views
-2

我無法弄清楚是什麼導致這個異常。它發生在reRead()方法中。java.lang.NullPointerException序列化

我測試過它沒有reRead()方法和其他一切正常。

public class SerFiles { 

    private ObjectInputStream in; 
    private ObjectOutputStream out; 
    private FileReader fr; 
    private FileWriter fw; 
    private BufferedReader br; 
    private BufferedWriter bw; 
    private StringTokenizer token; 
    private ArrayList<Product> prod = new ArrayList<Product>(); 
    private String line = "c"; 
    private Product proc; 

    private int a,b,d,e,f; 
    private String c; 

    public SerFiles(){ } 

    public void openFiles() 
    { 
     try 
     { 
      out = new ObjectOutputStream(new FileOutputStream("prod.ser")); 
      fr = new FileReader("SalesDelim.txt"); 
      br = new BufferedReader(fr); 

      System.out.println("OPEN SUCCESS"); 
     } 
     catch(Exception ex) 
     { 
      System.out.println(ex.toString()); 
     } 
    } 

    public void readAndWrite() 
    { 
     try 
     { 
      line = br.readLine(); 

      while(line != null) 
      { 
       if(line != null) 
       { 
        token = new StringTokenizer(line, "**"); 

        a = Integer.parseInt(token.nextToken()); 
        b = Integer.parseInt(token.nextToken()); 
        c = token.nextToken(); 
        d = Integer.parseInt(token.nextToken()); 
        e = Integer.parseInt(token.nextToken()); 
        f = Integer.parseInt(token.nextToken()); 

        prod.add(new Product(a,c,e,f)); 
        line = br.readLine(); 
       } 
      } 

      for(int i = 0; i<prod.size(); i++) 
      { 
       out.writeObject(prod.get(i)); 
      } 

      System.out.println("WRITE SUCCESS"); 
     } 
     catch(Exception ex) 
     { 
      System.out.println(ex.toString()); 
     } 
    } 

    public void reRead() 
    { 
     try 
     { 
      in = new ObjectInputStream(new FileInputStream("prod.ser")); //////ERROR HAPPENS HERE 

      while(true) 
      { 
       proc = (Product)in.readObject(); 
       System.out.println(proc.toString()); 
      } 
     } 
     catch(EOFException ioe){ 
      return; 
     } 
     catch(Exception ex) 
     { 
      System.out.println(ex.toString()); 
     } 
    } 

    public void closeFiles() 
    { 

     try 
     { 
      fr.close(); 
      br.close(); 
      out.close(); 
      in.close(); 

      System.out.println("CLOSE SUCCESS"); 
     } 
     catch(Exception ex) 
     { 
      System.out.println(ex.toString()); 
     } 
    } 
} 

我測試了它沒有reRead()方法,它工作正常。

謝謝

+0

我不相信'NullPointerException'會發生在那裏。發佈堆棧跟蹤。格式化您的代碼。只發布相關部分。 – 2014-10-19 21:26:36

+1

不要做System.out.println(ex.toString());'。做'ex.printStackTrace()';它提供了更多有用的信息。 – Pokechu22 2014-10-19 21:28:27

回答

0

嘗試:

in = new ObjectInputStream(new FileInputStream("prod.ser")); 

while (true) 
{ 
    proc = (Product)in.readObject(); 
    System.out.println(proc); // change!! 

    if (proc == null) break; // quit the loop 
} 

所以,問題是,你是在終場null調用toString()