Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why does this FileWriter create a null pointer? HELP!

807589Oct 9 2008 — edited Oct 9 2008
I'm trying to create a logging program that implements an interface. The FileWritter does its job and creates the file but any other method called on the file, such as add() or close() produces a null pointer? I used the variable "fw" for the FileWriter and fw.close seems to point to nothing. Please, help.

Source code:

public class FileSystemWarQuestLog implements WarQuestLog{

FileWriter fw;
boolean isRunning;
int elements;

public FileSystemWarQuestLog(){
isRunning = false;
elements = 0;
}

public void start() throws IllegalStateException, IOException {

if (fw != null){
throw new IllegalStateException("Logger is already running");
}
else{
FileWriter fw = new FileWriter("/home/drew/Desktop/WarQuestLog");
isRunning = true;
}
}

public void stop() throws IllegalStateException, IOException {

if (fw == null){
throw new IllegalStateException("Logger is not running");
}
else{
fw.close();
isRunning = false;
}
}

public boolean isRunning(){
return isRunning;
}

public int size(){
return elements;
}

public void clear() throws IllegalStateException, IOException{
FileWriter fw = new FileWriter("WarQuestLog");
BufferedWriter bw = new BufferedWriter(fw);
bw.close();

}

public void add(String s) throws IllegalStateException, IOException{
if (fw == null){
throw new IllegalStateException("Loger is not running");
}
else{
fw.write(s);
fw.flush();
elements++;
}
}
}

Heres a test harness is used to try and figure out what is happening:

public class harness{

public static void main (String[]args) throws IOException {

FileSystemWarQuestLog newLog = new FileSystemWarQuestLog();
newLog.start();
System.out.println(newLog.isRunning());
newLog.stop();
System.out.println(newLog.isRunning());
}
}

-which returns true and then the null pointer exception.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 6 2008
Added on Oct 9 2008
27 comments
1,262 views