ZAX
ZAX

Reputation: 1006

Writing Multiple Lines To A File At Different Times

I have the basics of my program finished.

The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.

My goal is to get all of this output into a text file.

Currently I create a scanner for reading:

static Scanner input = new Scanner(System.in);

Then in my main driver method I create a Formatter:

public static void main(String[] args) {
        Formatter output = null;
        try{
            output = new Formatter("output.txt");
        }
        catch(SecurityException e1){
            System.err.println("You don't have" +
                    " write accress to this file");
            System.exit(1);
        }
        catch(FileNotFoundException e){
            System.err.println("Error opening or" +
                    " creating file.");
            System.exit(1);
        }

After each time I expect output I have placed this bit of code:

output.format("%s", input.nextLine());

And finally I close the file with

output.close()

The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:

output.format("%d", i);

where i is an integer of 0 and the file writes correctly.

However, I cannot seem to get it to work for an entire line, or for the output at all.

Please help!

Upvotes: 0

Views: 1056

Answers (1)

Vineet Kosaraju
Vineet Kosaraju

Reputation: 5860

I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.

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

try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}

Upvotes: 1

Related Questions