-1

I am creating a HTML Webpage Generator as part of a college assignment. What I am trying to do is set the header by taking in the users text and saving it to string through the use of a get / set class. However when I try to output the text to file I get an error.

The code I am using to try and output the string is the following

public static void main(String[] args) throws IOException { 
        try { 
            File f = new File("C:\\Users\\David\\Desktop\\output.html");
            if(!f.exists()) { 
                f.createNewFile();
            }
            FileWriter fw = new FileWriter(f);
            fw.write(getHeader());
            fw.close();
        }catch(IOException io) { 
            Logger.getLogger(webPage.class.getName()).log(Level.SEVERE, null, io);
        }
    }

The error that Eclipse is giving me is

Exception in thread "main" java.lang.NullPointerException
    at java.io.Writer.write(Unknown Source)
    at webPage.main(webPage.java:49)

Can anyone help me correct this please?

user2978884
  • 47
  • 1
  • 10
  • 1
    `getHeader()` returns null. SO that's the method that you should fix. – JB Nizet Apr 13 '14 at 17:15
  • @JBNizet I have a class called Header which should set the header through wp.setHeader( // code here ). Why would it be null when I am sending text through to it to set the string in the get / set class? – user2978884 Apr 13 '14 at 17:25
  • I can't tell anything without seeing the code. Just add `System.out.println(getHeader())` before writing it to your FileWriter, and see by yourself. Or use your debugger. – JB Nizet Apr 13 '14 at 18:19

1 Answers1

0

As JB Nizet's comment mentions, FileWriter.write() will throw an exception if the argument is null.

If you replace your write with fw.write("Hello World"), you will find no NPE.

So you need to figure out why getHeader() is returning null and fix that.

merlin2011
  • 71,677
  • 44
  • 195
  • 329