Write to existing file?

edited November 2013 in Programming Questions

The only way I can find to write to a file is by creating it. E.g. output = createWriter("positions.txt");. The problem is that I want to log values from every time that I open the program in the same file. Is there any way that I can do this? This is just example code but it is my problem in a nutshell:

PrintWriter output;
void setup() {
  output = createWriter("positions.txt"); 
}
void draw() {
  output.println(mouseX + "t" + mouseY); // Write the coordinate to the file
  output.flush(); // Writes the remaining data to the file
}
Tagged:

Answers

  • I suggest to search logging or append to file from the main site. This question comes up often (might be worth a Technical FAQ entry...).

  • A simple example; but lacking loading: 3:-O

    // forum.processing.org/one/topic/saving-mouseevent-data-in-an-array
    // forum.processing.org/two/discussion/160/exporting-data
    
    import java.util.List;
    
    final static List<PVector> coords = new ArrayList();
    
    final static color BG = -1, FG = 0300, BORDER = 0;
    final static short DIM = 20, BOLD = 2, FPS = 100;
    
    void setup() {
      size(640, 480);
      smooth();
      noLoop();
      frameRate(FPS);
    
      fill(FG);
      stroke(BORDER);
      strokeWeight(BOLD);
      background(BG);
    }
    
    void draw() {
      print(coords.size() + " - ");
    }
    
    void mouseDragged() {
      redraw();
      coords.add( new PVector(mouseX, mouseY) );
      ellipse(mouseX, mouseY, DIM, DIM);
    }
    
    void keyTyped() {
      if (key != ' ' & key != RETURN & key != ENTER)  return;
    
      final String archive = dataPath("MouseCoords.txt");
    
      final int num = coords.size();
      final String[] coordsTxt = new String[num];
    
      for (int i = 0; i != num; ++i) {
        //final PVector coord = coords.get(i);
        //coordsTxt[i] = coord.x + "," + coord.y;
    
        final int[] coord = int( coords.get(i).array() );
        coordsTxt[i] = coord[0] + "," + coord[1];
      }
    
      saveStrings(archive, coordsTxt);
      println("\n\nMOUSE COORDS SAVED!\n");
    }
    
  • saveStrings() not really that helpful in this case, i don't think. having to save your entire history every run (and possible previous runs) and then output that at the end would make for pretty terrible logging.

    better just to open a file in append mode, and write the necessary information. unfortunately the processing helper method that saves you having to worry about writers and output streams and all that stuff doesn't give you an append flag.

    stackoverflow recommends the following java:

    try {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true))); // true = append
        out.println("the text");
        out.close();
    } catch (IOException e) {
        //oh noes!
    }
    

    but i haven't tried that in processing (probably needs extra imports?) and opening and closing the file everytime you want to write something is probably sub-optimal.

    anyone had any luck with log4j, say, and processing?

  • One of the things you can find with the search I suggested...

    http://bazaar.launchpad.net/~philho/+junk/Processing/view/head:/_SmallPrograms/Email/Logger.java

    Not super-efficient, indeed, but as long as you don't write megabytes of data per second, it should be OK.

  • edited November 2013

    I used this and made a simple example to quickly enter 3D points into a file.

    import java.io.*;
    
    /**
     * Simple logger.
     * @author Philippe Lhoste
     */
    
    
    //
    
    Logger loggerObject;  // don't use new here please
    
    float currentZ = -100; 
    
    // final int ballWidth = 12; 
    
    //
    // -----------------------------------------------------------
    //
    void setup()
    {
      // init
      size(800, 600);
      // this must be after the command size : 
      loggerObject = new Logger (sketchPath("") + "\\data1.txt");  // use new here please
      println ("click mouse to save points to file. Press space key: you change the virtual depth now by clicking mouse in X dir. Y dir is ignored ") ;
    } // func 
    //
    //
    void draw() 
    { 
      background(255);
      if (keyPressed) 
        println ("you change the virtual depth now by clicking mouse in X dir. Y dir is ignored; with -1 * map(mouseX,0,width,-100,width-100). " + currentZ) ;
    } // func 
    //
    
    // ==============================================
    
    void mousePressed() {
      //
      if (keyPressed && key==' ') {
        currentZ = -1* map (mouseX, 0, width, -100, width-100);
        println ("you change the virtual depth now by clicking mouse in X dir. Y dir is ignored; with -1 * map(mouseX,0,width,-100,width-100). " + currentZ) ;
      }
      else {
        loggerObject.log(str(mouseX)+","+str(mouseY)+","+currentZ);
      }
    }
    
    // ==================================================
    
    void mouseReleased() {
      //
    }
    
    
    // ============================================
    
    class Logger
    {
      String m_fileName;
    
      Logger(String fileName)
      {
        m_fileName = fileName;
      }
    
      void log(String line)
      {
        PrintWriter pw = null;
        try
        {
          pw = GetWriter();
          pw.println(line);
          println(line);
        }
        catch (IOException e)
        {
          e.printStackTrace(); // Dumb and primitive exception handling...
          println("ouch 1");
        }
        finally
        {
          if (pw != null)
          {
            pw.close();
          }
        }
      }
    
      void log(String[] lines)
      {
        PrintWriter pw = null;
        try
        {
          pw = GetWriter();
          for (int i = 0; i < lines.length; i++)
          {
            pw.println(lines[i]);
          }
        }
        catch (IOException e)
        {
          e.printStackTrace(); // Dumb and primitive exception handling...
          println("ouch 2");
        }
        finally
        {
          if (pw != null)
          {
            pw.close();
          }
        }
      }
    
      void log(String errorMessage, StackTraceElement[] ste)
      {
        PrintWriter pw = null;
        try
        {
          pw = GetWriter();
          pw.println(errorMessage);
          for (int i = 0; i < ste.length; i++)
          {
            pw.println("\tat " + ste[i].getClassName() + "." + ste[i].getMethodName() +
              "(" + ste[i].getFileName() + ":" + ste[i].getLineNumber() + ")"
              );
          }
        }                         
        catch (IOException e)
        {
          e.printStackTrace(); // Dumb and primitive exception handling...
          println("ouch 3");
        }
        finally
        {
          if (pw != null)
          {
            pw.close();
          }
        }
      }
    
      private PrintWriter GetWriter() throws IOException
      {
        // FileWriter with append, BufferedWriter for performance
        // (although we close each time, not so efficient...), PrintWriter for convenience
        return new PrintWriter(new BufferedWriter(new FileWriter(m_fileName, true)));
      }
    }
    // =================================================
    
Sign In or Register to comment.