2012-08-16 199 views
0

Noob问题。必须定义一个显式构造函数错误Java

卡住以下代码。获取“默认构造函数不能处理由隐式超级构造函数抛出的异常类型IOException异常。必须定义一个明确的构造函数”错误的线条以粗体显示

private FileWriter fileWriter = new FileWriter(file); 具体来说,我的问题是.....我如何为filewriter创建一个显式构造函数?

第二个问题:我知道方法appendtoLog不正确。我只想要这个方法来做bufferWriter.write(logInfo),但为此我需要调用已经创建的bufferWriter对象。但正如你所看到的,我已经在另一个方法中实例化了它,防止它被appendtolog方法使用。请在我的方法中建议解决方案或错误。

任何帮助? 谢谢。

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.io.File; 
import java.io.FileWriter; 
import java.io.BufferedWriter; 
import java.io.IOException; 

public class Logging { 


private DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); 
private Date date = new Date(); 
private File file = new File("c:\\view\\" + dateFormat.format(date) + "\\" 
     +"\\SmokesLog.txt"); 
private FileWriter fileWriter = **new FileWriter(file);** 

public void createLogFile() throws Exception { 
try{ 
if(!file.exists()){ 
    file.createNewFile(); 
    System.out.println("file name is "+ file.getName()); 
     BufferedWriter bufferWriter = new BufferedWriter(new  
    FileWriter(file.getName(),true)); 
     bufferWriter.write("Log Started for Test"); 
} 
    } catch (IOException e) { 
      System.out.println("code failed in creating logfile"); 
    } 

} 

public void appendToLog(String logInfo) throws IOException { 
    System.out.println("code got to appendToLog method"); 
    // below does not append.need to find better method. 
    if (file.exists()) { 
     BufferedWriter bufferWriter = new BufferedWriter(fileWriter); 
     bufferWriter.write(logInfo); 
     System.out.println("Done"); 
    } 
} 
} 
+2

是不是有一个原因,你不只是使用[一个正确的日志库](http://logback.qos.ch/)或'java.util.logging'? – 2012-08-16 01:25:45

回答

1

正如人们所说,这是因为创建FileWriter会引发异常。虽然我建议使用Logger包代替,但您可以通过以下方法解决此问题:

使用显式构造函数,捕获该异常,并且很可能重新抛出它包装在RuntimeException中。

private FileWriter fileWriter; 

public Logging() { 
    super(); 
    try { 
     fileWriter = new FileWriter(file); 
    } 
    catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

或使用实例初始化块,它在你的构造超()任何调用后执行,但在此之前在构造函数中的任何其他代码。在你的情况下,如果你没有构造函数,调用一个隐式的super(),这是可以的,因为你在扩展Object。所以初始化块在那之后立即执行。所以以下几乎在功能上等同于上面的代码。正如我所说,我不建议这样做,但真正的日志包(slf4j + log4j)会更合适。

1

由于线路可能导致异常,您必须在您Logging)和的构造函数初始化它执行正确的异常处理,不FileWriter

您不能在可能导致异常的隐式构造函数中使用代码。

重新思考何时创建日志文件。例如,在文件尚未打开时调用createLogFile。

+0

谢谢。这有帮助。 – user1525831 2012-08-16 17:10:35

0

它看起来像你只是为你的应用程序做一个记录器,但我建议使用像Log4j这样的开源记录库或者propper记录库,而不是重新创建已经存在的东西(并且定期支持)。

Short introduction to log4j: Ceki Gülcü, March 2002

用法:

BasicConfigurator.configure(); 

Logger logger = Logger.getLogger("Foo"); 

logger.debug("Hello World"); 
logger.warn("it's me"); 

输出: Logging OptionClassOutput

0 [main] DEBUG Foo - Hello World 
1 [main] WARN Foo - it's me 

下载:here

相关问题