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

问题描述 投票:0回答:1

我正在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

processing println
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.