Noob Question.
Stuck on the following code. Getting “Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor” error for the line in bold
private FileWriter fileWriter = new FileWriter(file);
To be specific, my question is …..how do i create a explicit constructor for filewriter?
2nd issue: i know method appendtoLog is incorrect. I only want this method to do bufferWriter.write(logInfo) but for that i need to call the bufferWriter object already created.But as you can see, i have instantiated it in another method which prevents it from being available to appendtolog method. Pls suggest solutions or mistake in my approach.
Any help?
Thanks.
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");
}
}
}
As people have said, it’s because creating a FileWriter throws an exception. While i do recommend using a Logger package instead, here’s a way you can overcome this:
Use an explicit constructor, catch the exception, and most likely rethrow it wrapped in a RuntimeException.
OR use an instance initializer block, which executes after any call to super() in your constructor, but before any other code in your constructor. In your case, if you don’t have a constructor, an implicit super() is called, which is OK, because you’re extending Object. So the initializer block executes immediately after that. So the following is pretty much functionally equivalent to the above code.
As i said, i don’t recommend doing it this way though, and a real logging package (slf4j + log4j) would be more appropriate.