2012-10-30 149 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代码应该在构造函数中。