Christian Baker
Christian Baker

Reputation: 389

Formatter not writing to file

I'm trying to write some strings to a file called "file.txt" but when I run the program, nothing is written. If the file does not exist, it will create the file, but write nothing.

public class CreateTextFile 
{
    private Formatter output;

    public void openFile(String filename)
    {
        {
            try
            {
                output = new Formatter(filename);
            }
            catch(FileNotFoundException fileNotFoundException)
            {
                System.err.println("Error");
            }
        }
    }

    public void addText()
    {
        Random randomnumber = new Random();
        int lines = 1 + randomnumber.nextInt(10);

        String text[] = new String[lines];

        output.format("%s","Hello");

        /*for (int i = 0; i < lines; i++)
        {
            Textline tokens = new Textline("Hello",1);
            output.format("%s",tokens.toString());
        }*/
    }
}

Upvotes: 1

Views: 7136

Answers (2)

grkvlt
grkvlt

Reputation: 2627

The output from a java.util.Formatter is not written immediately, but is buffered in memory first. Note the documentation for the file argument to the constructor you used, at http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.io.File)

The file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

Since the Formatter class implements both the Flushable and Closeable, interfaces it has flush() and close() methods. To flush buffered data to disk, call flush() and the waiting data will be written immediately. Then, once you are finished using the Formatter call close() and the remaining buffered data will be written out.

So, for example, you could have code like this after formatting each bit of data:

output.format("%s","Hello");
output.flush();

Or, to make sure everything is written out even if there is an exception, use a finally block to call the close() method:

Formatter output = new Formatter("file.txt");
try {
    // your code
} finally {
    output.close();
}

If you're using Java 7.0 then because Formatter also implements AutoCloseable a try-with-resources block could be used instead of the finally block:

try (Formatter output = new Formatter("file.txt") {
    // your code
}

This automatically calls close() when the block completes.

Upvotes: 1

Reimeus
Reimeus

Reputation: 159784

Close the Formatter once all formatting is complete

output.close();

Upvotes: 3

Related Questions