Save and load string from text file

try this, but it expects that the file with one line and one number in it already exists.

int myscore = 0;

String filename = "data/scores.txt";     // ! file must exists, have one line with one integer
String[] lines;

void setup() {
  size(200, 200);
  lines = loadStrings(filename);
  println("read scores from "+filename);
  println("got "+lines.length+" lines ");
  for ( int i =0; i<lines.length; i++) println("i "+i+" "+lines[i]);
  myscore = int(lines[0]);
  println("myscore "+myscore);
}

void draw() {
  myscore = int(random(7, 78));
}

void keyPressed() {
  if ( key == 's' ) {
    lines[0] = str(myscore);
    saveStrings(filename,lines);
    println("saved to "+filename);
    exit();
  }
}


2 Likes