2016-12-24 45 views
0

我有類客戶和客戶爪哇 - 如何避免NullPointerException異常,當我讀到一個空文件

數組列表,我要讀的對象形成客戶的文件,並添加他們的方法到陣列列表

import java.util.*; 
import java.io.*; 

public void readFile(File customerFile) throws IOException, NullPointerException { 
    ObjectInputStream OIS = null; 

    try { 
     FileInputStream FIS = new FileInputStream(customerFile); 
     OIS = new ObjectInputStream(FIS); 

     Customer customerObj = null; 

     while (true) { 
      customerObj = (Customer) OIS.readObject(); 
      this.customerList.add(customerObj); 
     } 
    } catch (Exception ex) { 
     System.out.println("(Exception : " + ex.toString() + ")"); 
    } finally { 
     OIS.close(); 
     if (!isEmpty()) { 
      Print(); // print the customerList 
     } else { 
      System.out.println("The Customer List Is Empty !"); 
     } 
    } 
} 

那麼,任何人都可以幫助我嗎?

NullPointerException異常在OIS.close();

+3

'FileName.length()== 0'檢查此條件是否爲空文件。 –

回答

0

您可以使用這樣的代碼:

public void readFile(File customerFile) throws IOException, NullPointerException { 
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(customerFile))) { 
     Customer customerObj = null; 

     while (true) { 
      customerObj = (Customer) ois.readObject(); 
      this.customerList.add(customerObj); 
     } 
    } catch (Exception ex) { 
     System.out.println("(Exception : " + ex.toString() + ")"); 
    } 

    if (!isEmpty()) { 
     Print(); // print the customerList 
    } else { 
     System.out.println("The Customer List Is Empty !"); 
    } 
} 

在我的代碼我使用try-with-resources聲明。它會自動關閉你的InputStream