How to add text to csv / txt file in the Processing section?

I use this simple code to write several lines to a file called "example.csv", but every time I run the program, it overwrites the existing data in the file. Is there any way to add text to it?

void setup(){ PrintWriter output = createWriter ("example.csv"); output.println("a;b;c;this;that "); output.flush(); output.close(); } 
+4
source share
3 answers
 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(); } } 
+8
source

Read the file data, add new data to it and write the added data back to the file. Unfortunately, processing does not have a true “add” mode for writing a file.

0
source

You need to use FileWriter (pure Java (6 or 7)), not PrintWriter from the processing API. FileWriter has a second argument in the constructor that allows you to set a boolean value to decide whether you will add an output or overwrite it (true to add, false to overwrite).

The documentation is here: http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html Note that you can also use BufferedWriter and pass it to the FileWriter constructor in the constructor, if at all helps (but I do not consider it necessary in your case).

Example:

 try { FileWriter output = new FileWriter("example.csv",true); //the true will append the new data output.println("a;b;c;this;that "); output.flush(); output.close(); } catch(IOException e) { println("It Broke :/"); e.printStackTrace(); } 

As above, this will work in PDE - and in Android - but if you need to use it in PJS, PyProcessing, etc. then you have to hack it

  • dynamically read the length of an existing file and store it in an ArrayList
  • add new line to ArrayList
  • use the ArrayList index to control where in the file you are currently writing.

If you want to suggest an improvement to the PrintWriter API (which is probably based on FileWriter), you can do this on the "Handling Issues" page on GitHub:

https://github.com/processing/processing/issues?state=open

0
source

Source: https://habr.com/ru/post/1485286/


All Articles