【问题标题】:Processing saving to .txt file?正在处理保存到 .txt 文件?
【发布时间】:2017-04-10 12:46:53
【问题描述】:

我不知道如何在处理中保存到 txt 文件,我尝试了一些不同的东西,但每次似乎文件都被覆盖,因为:

output = createWriter("positions.txt");

如果我尝试删除这一行,或者尝试其他方法来检查文件是否坚持然后不运行该行,我会出现 NullPointerException。

有什么方法可以在不覆盖文件的情况下保存文件?

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
}

【问题讨论】:

  • 文件被覆盖,因为您使用的是相同的路径"positions.txt"。如果您想每次都创建一个新文件,请使用whilefor 循环遍历数字以检查"positions" + number + ".txt" 是否存在。继续前进,直到文件不存在并将其用作您的路径。
  • @khelwood 这是处理而不是 Java - createWriter 是处理的本机函数。考虑到这一点,op - Processing != Java,因此值得删除 Java 标记。

标签: java file printing output processing


【解决方案1】:

如您所见,Processing 的 createWriter() 函数每次调用时都会创建一个新文件。

如果您在 Google 上搜索“处理追加到文本文件”或“Java 追加到文本文件”,您会得到大量结果。

基本上,您想使用 Java 的 PrintWriter 类,其构造函数采用 boolean 参数。如果该参数是true,您的数据将被附加到文件的末尾,而不是覆盖原始数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多