-1

This is my code:

package net.james.filewrite;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import net.james.game.WarGame;

public class NewWriting {
 public static FileWriter filewriter;
 public static WarGame wg = new WarGame();
 public static File f = new File("High Score.txt");


 public static void createFile(){
     try {
         filewriter = new FileWriter("High Score.txt", true);
         System.out.println("Creating file");
     } catch (IOException e) {
         e.printStackTrace();
     }
 }


 public static void write(){
     try {
         filewriter.write("hi"); //<< line 27
         filewriter.flush();
     }catch (IOException e) {
         e.printStackTrace();
     }
 }

 public static void fileExists(){
     if (!f.exists()){
         System.out.println("NOPE!!!");
         createFile();
         write();
         System.out.println("now it does!");
     }else{
         System.out.println("YEP!");
         write();
     }


 }
}

When ever I call the 'write' method it just says:

Exception in thread "main" java.lang.NullPointerException at net.james.filewrite.NewWriting.write(NewWriting.java:27)

If anyone can help me. I would be very greatful.

  • 1
    Are you calling `createFile()` before you call `write()`? That NullPointerException can only occur on that line when `filewriter` is null, and since it's initialized/assigned in `createFile()`, I can only assume you're not calling that first. – Craig Otis Nov 20 '13 at 20:06
  • Where's your main method? How are you actually calling this? – Andrew Nov 20 '13 at 20:07

2 Answers2

0

You are assinging a value to filewriter in the createFile() method (which is only called if the file does not exist). If the file already exists createFile() will not be called and filewriter stays null. Within write() you then try to call filewriter.write(..) which fails because filewriter is null.

micha
  • 47,774
  • 16
  • 73
  • 80
0

If your file f exists, createFile will never get called, and you will never instantiate your filewriter

if (!f.exists()){
    System.out.println("NOPE!!!");
    createFile();
    write();
    System.out.println("now it does!");
}
else
{
     System.out.println("YEP!");
     write();  
}

So you should either delete your file(from code) when you initialize your program, or you should be able to handle cases where the file already exists. It depends on what behavior you want