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}
} 

当我调用记录数据时,如果出现问题,它将向调用类返回 false。我可以留言。

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

   }
 }
 }
 } 
4

1 回答 1

1

构造函数不应该做任何事情。构造函数是与对象分配密切相关的初始化阶段。

应该避免抛出异常,或者在构造函数中做任何可能抛出异常的事情。

Java没有将分配和初始化阶段分开,没有代码,尤其是IO代码应该在构造函数中。

于 2012-10-30T09:44:11.217 回答