java - 如何在 Processing 中将文本附加到 csv/txt 文件?

标签 java csv processing

我使用这个简单的代码将几个字符串写入名为“example.csv”的文件,但每次运行该程序时,它都会覆盖文件中的现有数据。有没有办法将文本附加到它?

void setup(){
  PrintWriter output = createWriter ("example.csv");
  output.println("a;b;c;this;that ");
  output.flush();
  output.close();

}

最佳答案

import java.io.BufferedWriter;
import java.io.FileWriter;

String outFilename = "out.txt";

void setup(){
  // Write some text to the file
  for(int i=0; i<10; i++){
    appendTextToFile(outFilename, "Text " + i);
  } 
}

/**
 * Appends text to the end of a text file located in the data directory, 
 * creates the file if it does not exist.
 * Can be used for big files with lots of rows, 
 * existing lines will not be rewritten
 */
void appendTextToFile(String filename, String text){
  File f = new File(dataPath(filename));
  if(!f.exists()){
    createFile(f);
  }
  try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
    out.println(text);
    out.close();
  }catch (IOException e){
      e.printStackTrace();
  }
}

/**
 * Creates a new file including all subfolders
 */
void createFile(File f){
  File parentDir = f.getParentFile();
  try{
    parentDir.mkdirs(); 
    f.createNewFile();
  }catch(Exception e){
    e.printStackTrace();
  }
}    

关于java - 如何在 Processing 中将文本附加到 csv/txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010222/

相关文章:

javascript - 处理、镜像或翻转图像而不影响其他图像

java - 卡在 while 循环中。进行中

email - 为什么 CSV 附件会在正文中显示为文本?

java - 在处理中创建第二个小程序(窗口)

java - java.sql.PreparedStatement 的 Android 实现

java - 无法从 Karaf 2.2.0 OSGi 容器中的根上下文运行 WAR

mysql - Oracle到Mysql时间戳数据未导入

javascript - 使用 JavaScript for IE 在本地读取 CSV 文件,无需 FileReader API

java - 我知道如何找到中点,但在这段代码中,我不确定如果我们添加它的值,将如何计算中点

java netty/nio connect 在 windows 2003 上产生过多的中断