How to save text into new txt everytime you save it

edited December 2017 in Questions about Code

This is the code, this code saves the written text into a txt, but it always saves it into the same one, so the older text written in the txt file gets deleted. I would like it to save it into a new txt everytime the program saves it . How do i do so.

and another thing: how do i load the text in txt into the document, by clicking on another button :)

thanks in advance :)

String str = "";

void setup(){
  size(400,400);
}

void draw(){
  background(0);
  fill(255);
  text(str,20,20,100,height-20);
  fill(128);
  if( over() ){
    fill(196);
  }
  rect(width-20,height-20,20,20);
}

boolean over(){
  return( mouseX>width-20 && mouseY > height-20 );
}

void keyPressed(){
  if( keyCode == DELETE || keyCode == BACKSPACE ){
    if( str.length() > 0 ){
      str = str.substring(0, str.length()-1);
    }
  } else {
    if( key != CODED ){
      str += key;
    }
  }
}

void mousePressed(){
  if( over() ){
    saveIt();
  }
}

void saveIt(){
  String[] strs = { str };
  saveStrings( "text.txt", strs );
}

Answers

  • New file name: you could make a nee file name based on the date today and the time including seconds - see reference, it’s all there

    For a file open dialogue see

    https://processing.org/reference/selectInput_.html

  • edited December 2017

    Is it possible for you to make an example for me

  • A file dialog to choose a file can be found by checking previous posts as well: https://forum.processing.org/two/search?Search=selectinput

    Also check the controlP5 or G4P library to use buttons in your sketch. You can install either library using the library manager in the Processing IDE. Then, go to files>>examples>>Contributed libraries and either ControlP5 or G4P to see the examples.

    Kf

  • The only thing that i would like to is use the loadStrings(), buti don't really know how to load the txt file as text.

  • the other thing is to make sure when i save the file it saves it into a txt, and when i save another time it saves it into another txt not the same as before that but new

  • it saves it into another txt not the same as before that but new

    i told you how to do this

    you need a file dialog to select a text file. after that you can use loadStrings

  • @Caseguy

    Check the reference and run the code provided there. Become familiar with the main components of a Processing sketch and run the examples. When you find a code that could potentially work for you, and you have a specific question, provide your code and all the details.

    You can also check previous posts and find something that fits your needs. Try searching loadStrings for example.

    Kf

  • I have tried the SelectInput(), but i cant seem to make it work :(

  • Show your code and we look into it

  • It's above

  • No, that's MY code. We want YOUR code. Show us what changes you have tried to make to it.

  • This really didn't need to be a new Question, you could've just continued the old one.

    Also, you've posted someone else's code without credit, which is a bit of a crappy thing to do, not to mention confusing.

  • Sry I will never post more, I forgot to mention TfGuy44. Bye :)

  • edited December 2017

    See, the idea of the forum is that you ask for help with your code. Like post code and ask something like „in line 30 I need to check the mouse against my nice Load Button but I don’t know how“.

    The forum is not here to ask others for complete programs.

    These are just some rules here to get used to.

    Now you wrote you tried selectInput and I asked to see your attempt and you said it’s above but above there is no selectInput.

    So when you want to learn how to program, try to write a code with selectInput and then show attempts and ask and learn.

    The trick with selectInput for example is that draw() doesn’t wait for it. Instead you need to check whether its result has arrived and then move on. Use a Boolean variable for example which tells you if the result has arrived (see example of selectInput to understand).

    Best regards, Chrisir

  • Of course instead of saving with a date / time file name there is also a normal selectOutput dialog, so the user can type a file name and select a folder. See reference selectOutput

    Are you using Windows?

  • I'm using windows

    And this is TFGuys code: I tried to use it as you said but can't figure it out.

    void fileSelected(File selection) {
      if (selection == null) {
        println("Window was closed or the user hit cancel.");
      } else {
        println("User selected " + selection.getAbsolutePath());
      }
    }
    
    
    
    String str = "";
    
    void setup(){
      size(400,400);
      selectOutput("Select a file to write to:", "fileSelected");
    
    }
    
    void draw(){
    
    
    
      background(0);
      fill(255);
      text(str,20,20,100,height-20);
      fill(128);
      if( over() ){
        fill(196);
      }
      rect(width-20,height-20,20,20);
    
    }
    
    boolean over(){
      return( mouseX>width-20 && mouseY > height-20 );
    }
    
    void keyPressed(){
      if( keyCode == DELETE || keyCode == BACKSPACE ){
        if( str.length() > 0 ){
          str = str.substring(0, str.length()-1);
        }
      } else {
        if( key != CODED ){
          str += key;
        }
      }
    }
    
    void mousePressed(){
      if( over() ){
        saveIt();
      }
    }
    
    void saveIt(){
      String[] strs = { str };
      saveStrings( "text.txt", strs );
    }
    
  • String str = "Test 17";
    
    // state of the program :
    //constants, unique: 
    final int normal = 0;
    final int save   = 1;
    final int load   = 2;
    ///current state 
    int state=normal;
    
    boolean blinkIsOn=true; 
    
    String savePath=""; 
    String loadPath=""; 
    
    // ------------------------------------------------
    // Core functions of processing 
    
    void setup() {
      size(900, 900);
    }//func 
    
    void draw() {
    
      switch (state) {
    
      case normal:
        drawForStateNormal() ;
        break; 
    
      case save:
        // wait 
        if (!savePath.equals("")) {
          // waiting is over
          saveIt();
          // go back 
          state=normal;
        }
        break; 
    
      case load:
        // wait 
        if (!loadPath.equals("")) {
          // waiting is over
          loadIt();
          // go back 
          state=normal;
        }
        break;
    
      default:
        //Error 
        println("Fail");
        exit();
        break; 
        //
      }//switch
    }//func
    
    // ------------------------------------------------
    
    void drawForStateNormal() {
    
      background(0);
    
      textSize(14);
    
      // title 
      fill(255, 2, 2);
      text("My little Editor", 
        width-123, 20, 100, 22);
    
      // the text the user entered 
      fill(255);
      text(str+blink(), 
        20, 20, 100, height-20);
    
      // ----------------------
      // TWO buttons
      textSize(11);
      fill(128);
      if ( overSave() ) {
        fill(196);
      }
      rect(width-40, height-20, 40, 20);
      fill(255); 
      text("Save", 
        width-40+4, height-9+3);
    
      // ---
      fill(128);
      if ( overLoad() ) {
        fill(196);
      }
      rect(width-40, height-50, 40, 20);
      fill(255); 
      text("Load", 
        width-40+4, height-50+9+3);
    }
    
    //----------------------------------------------------------------------------
    // TWO functions register if mouse is over buttons 
    
    boolean overSave() {
      return( mouseX > width-40 && 
        mouseY > height-20 );
    }
    
    boolean overLoad() {
      return( mouseX > width-40 && 
        mouseY > height-50  && 
        mouseY < height-50+25 );
    }
    
    // ---------------------------------------------------------------------------
    // Inputs 
    
    void keyPressed() {
      if ( keyCode == DELETE || keyCode == BACKSPACE ) {
        if ( str.length() > 0 ) {
          str = str.substring(0, str.length()-1);
        }
      } else {
        if ( key != CODED ) {
          str += key;
        }
      }
    }
    
    void mousePressed() {
      if ( overSave() ) {
        savePath=""; 
        selectOutput("Select a file to write to:", "fileSelectedSave");
        state=save;
      } else if  ( overLoad() ) {
        loadPath=""; 
        selectInput("Select a file to load:", "fileSelectedLoad");
        state=load;
      }
    }
    
    // -------------------------------------------------
    // Save and load 
    
    void saveIt() {
      //save
      // split at line break and make array 
      String[] strs = split ( str, "\n" );
      saveStrings( savePath, strs );
    }
    
    void loadIt() {
      // load
      String[] strs = loadStrings( loadPath );
      str=join(strs, "\n");
    }
    
    void fileSelectedSave(File selection) {
      if (selection == null) {
        println("Window was closed or the user hit cancel.");
      } else {
        println("User selected " + selection.getAbsolutePath());
        savePath=selection.getAbsolutePath();
      }
    }
    
    void fileSelectedLoad(File selection) {
      if (selection == null) {
        println("Window was closed or the user hit cancel.");
      } else {
        println("User selected " + selection.getAbsolutePath());
        loadPath=selection.getAbsolutePath();
      }
    }
    
    // -------------------------------------------------
    // Misc
    
    String blink() {
      // toggle blinkIsOn
      if (frameCount%17 == 0) 
        blinkIsOn=!blinkIsOn;
    
      // depending from blinkIsOn 
      if (blinkIsOn) 
        return "|";
      else return "";
    }
    //
    
  • still room for improvement, e.g. what happens when "Window was closed or the user hit cancel."

  • FFS, just have a counter.

    int counter = 0;
    
    saveStrings( "text" + counter + ".txt", strs );
    counter++;
    
  • I'm guessing this is homework. Who needs to write a text editor in this day and age?

  • Thanks for trying to help Chrisir. I made my own program, didn't use TfGuy44 code, I got live help, wich very much usefull.

    And TfGuy44 thanks for trying to help me, but why do you have to be rude? I'm just a student that need help with some simple programming from the forum.

    And koogs It's for our exam, it's a part of our report(Yes you can call it homework).

  • Actually It's a very smart way you made your "|" line. Really like (If possible can i use it in mine ?)

  • Should i post the code I made, and yours here so if people finds this disscisuon they can get the help/code ? It's only 73 lines

  • Please do.

    The blink thing is not by me, by the way. It’s a variation of a Code by gotolooop iirc

  • String words = "";
    String[] wordOutPut;
    boolean blinkIsOn=true; 
    void setup() {
      size(750, 1000);
    }
    
    void draw() {
      background(255);
    
    
      //Button rectangle
      fill(150);
      //SaveButton
      rect(450, 850, 100, 50);
      //LoadButton
      rect(570, 850, 100, 50); 
      //Button text
      fill(0);
      textSize(20);
      textAlign(CENTER, CENTER);
      text("Save", width/1.5, 875);
      text("Load", width/1.2, 875);
      //Written text by user.
      textSize(18);
      textAlign(LEFT, TOP);
      textLeading(20);
      //(If you want to change where the text should be change this section (295, 340, 140, 200) = (X,Y,Height,Width) musch like a rect. 
      text(words+blink(), 295, 340, 140, 200);
    }
    //Makes it possible to write into the program
    void keyPressed() {
      if ( keyCode == DELETE || keyCode == BACKSPACE ) {
        if ( words.length() > 0 ) {
          words = words.substring(0, words.length()-1);
        }
      } else {
        if ( key != CODED ) {
          words += key;
        }
      }
    }
    
    
    //Start and Load buttons clicable // (Note the SAVE button also clears the text, if you want it to not save just remove the words = ""; from the first if statement)
    void mouseClicked() {
      if (mouseX > 450 && mouseX < 550 && mouseY > 850 && mouseY < 900) {
        String date = "Location" + "-" + day() + "-" + minute() + "-" + second() + ".txt";
        saveStrings(date, new String[]{words});
        words = "";
      }
      if (mouseX > 570 && mouseX < 670 && mouseY > 850 && mouseY < 900) {
        selectInput("Select a file to load", "fileSelected");
      }
    }
    //Loads the string into the program
    void fileSelected(File selection) {
      wordOutPut =  loadStrings(selection.getAbsolutePath());
      loadStrings(selection.getAbsolutePath());
      words = join(wordOutPut, "\n");
    }
    
    //Blinking line |
    String blink() {
      // toggle blinkIsOn
      if (frameCount%30 == 0) 
        blinkIsOn=!blinkIsOn;
    
      // depending from blinkIsOn 
      if (blinkIsOn) 
        return "|";
      else return "";
    }
    
  • new version

    // Editor 
    // from https : // forum.processing.org/two/discussion/comment/112902/#Comment_112902
    
    // editor path and file extension
    final String pathFolder="texts";
    final String fileExtension = ".txt";
    
    // editor content 
    String str = "Test ";
    
    // states of the program:
    // unique constants: 
    final int normal = 0;
    final int save   = 1;
    final int load   = 2;
    ///current state (must be one of them) 
    int state=normal;
    
    // blinking cursor:  
    boolean blinkIsOn=true; 
    
    // Paths 
    String savePath=""; 
    String loadPath=""; 
    
    // ------------------------------------------------
    // Core functions of processing 
    
    void setup() {
      size(900, 900);
    }//func 
    
    void draw() {
    
      switch (state) {
    
      case normal:
        drawForStateNormal() ;
        break; 
    
      case save:
        // wait for Save Dialog 
        waitForSaveDialog();
        break; 
    
      case load:
        // wait for Load Dialog 
        waitForLoadDialog();
        break;
    
      default:
        //Error 
        println("Fail");
        exit();
        break; 
        //
      }//switch
    }//func
    
    // ------------------------------------------------
    
    void drawForStateNormal() {
    
      background(0);
    
      textSize(14);
    
      // title 
      fill(255, 2, 2);
      text("My little Editor", 
        width-123, 20, 100, 422);
    
      // show the text the user entered 
      fill(255);
      text(str+blink(), 
        20, 20, width-170, height-20);
    
      // ----------------------
      // buttons
      textSize(11);
      fill(128);
      if ( overSave() ) {
        fill(196);
      }
      rect(width-40, height-20, 40, 20);
      fill(255); 
      text("Save", 
        width-40+7, height-9+5);
    
      // ---
      fill(128);
      if ( overLoad() ) {
        fill(196);
      }
      rect(width-40, height-50, 40, 20);
      fill(255); 
      text("Load", 
        width-40+7, height-50+9+5);
    
      // ---
      fill(128);
      if ( overNew() ) {
        fill(196);
      }
      rect(width-40, height-80, 40, 20);
      fill(255); 
      text("New", 
        width-40+7, height-80+9+5);
    }
    
    //----------------------------------------------------------------------------
    // functions to register if mouse is over buttons 
    
    boolean overSave() {
      return( mouseX > width-40 && 
        mouseY > height-20 );
    }
    
    boolean overLoad() {
      return( mouseX > width-40 && 
        mouseY > height-50  && 
        mouseY < height-50+25 );
    }
    
    boolean overNew() {
      return( mouseX > width-40 && 
        mouseY > height-80  && 
        mouseY < height-80+25 );
    }
    
    // ---------------------------------------------------------------------------
    // Inputs 
    
    void keyPressed() {
    
      if (state!=normal)
        return;
    
      // for the editor: 
      if ( keyCode == DELETE || keyCode == BACKSPACE ) {
        if ( str.length() > 0 ) {
          str = str.substring(0, str.length()-1);
        }
      } else {
        if ( key != CODED ) {
          str += key;
        }
      }
    }
    
    void mousePressed() {
    
      if (state!=normal)
        return;
    
      // for the buttons 
      if ( overSave() ) {
        initSave();
      }
      //---
      else if ( overLoad() ) {
        initLoad();
      }
      //---
      else if ( overNew() ) {
        str="";
      }
      //
    }//func
    
    // -------------------------------------------------
    // Save and load 
    
    void initSave() {
      // init save process 
      // reset
      savePath="";
      // make date time stamp (the expression nf(n,2) means leading zero: 2 becomes 02)
      String dateTimeStamp = year() 
        + nf(month(), 2) 
        + nf(day(), 2) 
        + "-" 
        + nf(hour(), 2)
        + nf(minute(), 2)
        + nf(second(), 2);
      // prepare fileDescription which occurs in the dialogue
      File fileDescription = new File( sketchPath()
        + "//"
        + pathFolder 
        + "//" 
        + dateTimeStamp
        + fileExtension);
      // open the dialog  
      selectOutput("Select a file to write to", "fileSelectedSave", fileDescription);
      // set state to wait
      state=save;
    }
    
    void initLoad() {
      // init load process 
      // reset
      loadPath="";
      // prepare fileDescription which occurs in the dialogue
      File fileDescription = new File( sketchPath()+"//"+pathFolder+"//"+"*" + fileExtension );
      // open the dialog
      selectInput("Select a file to load", "fileSelectedLoad", fileDescription);
      // set state to wait
      state=load;
    }
    
    void fileSelectedSave(File selection) {
      // the 'callback' function
      if (selection == null) {
        // println("Window was closed or the user hit cancel.");
        // go back 
        state=normal;
      } else {
        // println("User selected " + selection.getAbsolutePath());
        savePath=selection.getAbsolutePath();
      }
    }
    
    void fileSelectedLoad(File selection) {
      // the 'callback' function
      if (selection == null) {
        // println("Window was closed or the user hit cancel.");
        // go back 
        state=normal;
      } else {
        // println("User selected " + selection.getAbsolutePath());
        loadPath=selection.getAbsolutePath();
      }
    }
    
    void waitForSaveDialog() { 
      if (!savePath.equals("")) {
        // waiting is over
        saveIt();
        // go back 
        state=normal;
      }
    }
    
    void waitForLoadDialog() { 
      if (!loadPath.equals("")) {
        // waiting is over
        loadIt();
        // go back 
        state=normal;
      }
    }
    
    void saveIt() {
      // save
      // split at line break and make array (to save it)
      String[] strs = split ( str, "\n" );
      // check if file extension (fileExtension, e.g. .txt) is there 
      int len = savePath.length(); 
      if (len<4 || !savePath.substring( len-4 ).equals(fileExtension)) {
        // file Extension is not present, we have to add it
        savePath += fileExtension; // add the file Extension
      } 
      // save 
      println("Saved: " + savePath);
      saveStrings( savePath, strs );
    }
    
    void loadIt() {
      // load
      String[] strs = loadStrings( loadPath );
      str = join(strs, "\n");
    }
    
    // -------------------------------------------------
    // Misc
    
    String blink() {
      // toggle blinkIsOn
      if (frameCount%17 == 0) 
        blinkIsOn=!blinkIsOn;
    
      // depending from blinkIsOn 
      if (blinkIsOn) 
        return "|";
      else return "";
    }
    //
    
Sign In or Register to comment.