gpt4 book ai didi

java - 使用 PrintWriter 不输出到文件

转载 作者:行者123 更新时间:2023-12-02 13:25:13 26 4
gpt4 key购买 nike

我没有遇到编译错误,但我的代码没有向保存的文件输出任何内容。该代码确实创建了文件,但它们是空的。有人看到我做错了什么吗?

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>");
}
}

最佳答案

您需要使用:

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

实际保存文件。

关于java - 使用 PrintWriter 不输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com