2

I get no compiling errors, but my code does not output anything to the saved files. The code does create the files, but they're empty. Does anybody see what I did wrong?

public class CellAutomataTest {
  public static void main(String[] args)
  {
    int rule = 120;//Integer.parseInt(args[0]);
    int numGen = 5;//Integer.parseInt(args[1]);
    String fileStem = "ca";//args[2];
    int width = 400;//Integer.parseInt(args[3]);
    int height = 400;//Integer.parseInt(args[4]);

    CellAutomata test = new CellAutomata(numGen, rule);

    PrintWriter writer = null;
    try {
        writer = new PrintWriter(new FileWriter(fileStem + ".js"));
    } catch (IOException ex) {
        Logger.getLogger(CellAutomataTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    PrintWriter writer2 = null;
    try {
        writer2 = new PrintWriter(new FileWriter(fileStem + ".html"));
    } catch (IOException ex) {
        Logger.getLogger(CellAutomataTest.class.getName()).log(Level.SEVERE, null, ex);
    }

    writer.println("function draw() {");
    writer.println("var canvas = document.getElementById('CellAutomata');");
    writer.println("if (canvas && canvas.getContext) {");
    writer.println("var context = canvas.getContext('2d');");

    test.simulate(writer, width, height);

    writer2.println("<html>");
    writer2.println("<head>");
    writer2.println("<script src=\"" + fileStem + ".js></script>");
    writer2.println("<style type=\"text/css\">");
    writer2.println("canvas { border: 1px solid black; }");
    writer2.println("</style> </head>");
    writer2.println("<body onload=\"draw();\">");
    writer2.println("<h1>Cellular Automata with Rule " + rule + "</h1>");
    writer2.println("<canvas id=\"CellAutomata\" width=\"" + width + "\" height=\"" + height + "\">");
    writer2.println("<p>Your browser doesn't support canvas.</p>");
    writer2.println("</canvas> </body> </html>");
  }
}

1 Answer 1

8

You need to use:

writer2.flush();
writer2.close();

to actually save the file.

Sign up to request clarification or add additional context in comments.

2 Comments

In fact what he needs is to only close the file. Closing does flush what has been written to the output stream.
Thank you. I'm new to Java, so I did not know I had to include that. I should've known there was some command to do so. Anyways, now I'm saving to the file successfully, and have discovered that it's not creating the grid as suspected, so now the fun really begins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.