Why does nothing write to my file?

I have a program that I am working on and I have an issue with writing a string into my file. The file is created, but the string value that should be written into it ultimately does not get written. There are no syntax errors according to Eclipse, so I suppose it's a semantical error.

public boolean createFile()
{
    try
    {
        f = new File("house.txt");
        if(!f.exists())
        {
            f.createNewFile();
            exists = true;
        }
        else 
            exists = false;
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    return exists;
}

That's the method that creates the file. This next one is the method that actually writes to the file, which is successfully created. The action is derived from a JButton that, when pressed, should perform this:

if(evt.getActionCommand().equals("CONFIRM"))
    {
        attribute = txt.getText();
        try
        {
            createFile();
            fWriter = new FileWriter(f);
            String content = attribute;         
            BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();

        } catch (IOException e) 
        {
            e.printStackTrace();
        } 
    }
Jon Skeet
people
quotationmark

I strongly suspect you're getting exceptions logged - you should improve your exception handling anyway, but if you're going to log exceptions, you really need to look in the logs when things don't work!

This is almost certainly the problem:

fWriter = new FileWriter(f);
String content = attribute;         
BufferedWriter output = new BufferedWriter(new FileWriter(f));

You're creating two FileWriters for the same file. The first one's existence will stop the second one from being created properly.

However, there are plenty of other points you should note:

  • FileWriter always uses the platform default encoding. I far prefer to explicitly specify an encoding, usually UTF-8.
  • Creating a new FileWriter (or FileOutputStream) already creates the file if it doesn't exist, so your createFile method is pointless (unless you really need to check whether or not the file previously exists)
  • You should always close your stream resources in a finally block or using a try-with-resources statement in Java 7.

Libraries can make this sort of thing much simpler though. I would use Guava rewrite your whole code as:

if (evt.getActionCommand().equals("CONFIRM")) {
    Files.write(txt.getText(), new File("house.txt"), StandardCharsets.UTF_8);
}

Declare that your method can throw IOException, or catch it if you really want to handle it in the method.

If you really want to do it manually:

if (evt.getActionCommand().equals("CONFIRM")) {
  try (Writer writer = new OutputStreamWriter(
      new FileOutputStream("house.txt"), StandardCharsets.UTF_8)) {
    writer.write(txt.getText());
  }
}

people

See more on this question at Stackoverflow