gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:44:07 25 4
gpt4 key购买 nike

我使用这个简单的代码将几个字符串写入名为“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/

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