2012-10-30 147 views
0

我正在將數據寫入文件,當我寫這些數據時,我想這樣做,以便如果文件沒有打開,它會給用戶一條消息,指出什麼是錯誤的。我這樣做的方式是通過調用寫入的方法,如果失敗則返回false。這樣我可以提示用戶做一些事情來檢查發生了什麼。異常處理和構造函數

但是,當我創建的對象,我不能從構造函數返回任何東西,所以我有點難以應付我應該做什麼。

public class Writetofile { 
BufferedWriter writer = null; 

public Writetofile(String[]details) throws IOException{ 
String machine= details[0]; 
String date=details[1]; 
String start_time = details[2];  
try{ 
    File new_cal= new File("C:\\Activity_Calibrator\\log\\"+machine+"\\"+machine+date+".txt"); 
    new_cal.getParentFile().mkdir(); 
    FileWriter fwriter = new FileWriter(new_cal); 
    writer = new BufferedWriter(fwriter); 
    writer.write("Linear Calibratiton for " + machine + " carried out " + date+" ./n"); 
    writer.close(); 
    } 
catch(Exception e){ in here I would like to be able to send a message back to m 
code so that it can tell the user to check the folder etc} 
} 

當我調用記錄數據時,如果出現錯誤它將返回一個錯誤的調用類。我可以留言。

public boolean recordData(String record) throws IOException{ 
try{ 
    writer.append(record); 
    writer.close(); 
    return true; 
    } 
catch(Exception e){ 
    return false; 

    } 
} 
} 
} 

回答

1

構造函數不應該做任何事情。構造函數是一個與分配對象緊密相關的初始化階段。

要避免拋出異常,或者在可能拋出異常的構造函數中做任何事情。

Java沒有分離分配和初始化階段,沒有代碼,特別是IO代碼應該在構造函數中。