打印到文件仅打印最后一行

时间:2018-09-15 01:50:37

标签: processing println

我正在Processing.js中创建一个程序,以帮助我为像素图制作颜色渐变。斜坡生成器有效,因此现在我需要将我正在使用的HSV颜色转换为RGB的程序,以便可以将它们输入到我正在使用的程序中(它不允许我在某些情况下使用HSV颜色空间原因,但是我可以接受,因为我对这个程序很满意。

这是引起问题的功能

void convert(float h,float s,float v){
// h will be 0-360, s and v are 0-100
PrintWriter output;
output = createWriter("value.txt");
float S = s/100;
float V = v/100;
//the conversion algorithm I found expects s and v to be 0-1
float c = S*V;
float x = c*(1-abs(((h/60)%2)-1));
float e = V-c;
float R = 0.0;
float G = 0.0;
float B = 0.0;
if(0 <= h && h <= 60) {
R = c;
G = x;
B = 0;
} else if(60 <= h && h <= 120) {
R = x;
G = c;
B = 0;
} else if(120 <= h && h <= 180) {
R = 0;
G = c;
B = x;
} else if(180 <= h && h <= 240) {
R = 0;
G = x;
B = c;
} else if(240 <= h && h <= 300){
R = x;
G = 0;
B = c;
} else if(300 <= h && h <= 360) {
R = c;
G = 0;
B = x;
} else {
}
float r = R + e;
float g = G + e;
float b = B + e;
println(round(r*255)+","+round(g*255)+","+round(b*255));
output.println(round(r*255)+","+round(g*255)+","+round(b*255));
output.flush();
output.close();
}

未写入文件的println在控制台中显示得很好,但是output.println仅将最后一行写入文件。我期望有220行输出。如果需要,我可以编辑问题以获取其余的代码,但这是当前唯一会引起问题的函数。 Here's the source for the conversion algorithm I'm using

1 个答案:

答案 0 :(得分:0)

将来,请尝试将问题缩小到MCVE,如下所示:

void draw() {
  point(mouseX, mouseY);

  PrintWriter output = createWriter("positions.txt"); 
  output.println(mouseX);
  output.flush();
  output.close();
}

该程序显示了您遇到的相同问题,但是使用起来要容易得多。

问题是您在每帧创建一个新的PrintWriter。相反,您需要在开始时创建一次,并在程序运行时不断对其进行写入。

来自the reference

PrintWriter output;

void setup() {
  // Create a new file in the sketch directory
  output = createWriter("positions.txt"); 
}

void draw() {
  point(mouseX, mouseY);
  output.println(mouseX);  // Write the coordinate to the file
}

void keyPressed() {
  output.flush();  // Writes the remaining data to the file
  output.close();  // Finishes the file
  exit();  // Stops the program
}