# How to save data in a program

**URL:** <https://discourse.processing.org/t/how-to-save-data-in-a-program/35525>\
**Category:** Processing for Android\
**Created:** [March 2, 2022, 11:31pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525 "2022-03-02T23:31:40Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 2, 2022, 11:31pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/1 "2022-03-02T23:31:40Z")

</div>

Hello

I have been making a game and I wanted to know how you can save data in a game. For example you earned 10 points and when you close the app and reopen it, your progress will not be reset but the 10 points will stay.

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [March 2, 2022, 11:40pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/2 "2022-03-02T23:40:51Z")

</div>

Hello,

Take a look here:  
[https://processing.org/reference#output](https://processing.org/reference#output)

Experiment a little.

I was able to do this with _saveStrings()_ and _loadStrings()_

This code is not complete:

```auto
String [] saved;
int score;

void setup()
  {
  size(200, 200);
  //loadStrings()
  }

void draw()
  {
  }

void keyPressed()
  {
  score++;
  println(score);
  }

void mousePressed()
  {
  //saveStrings();
  }

```

I was able to store and recall a score with that basic template and a file to save these.  
There is code missing.

`:)`

---

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 3, 2022, 12:15am UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/3 "2022-03-03T00:15:09Z")

</div>

Thank you. Do you also know how to add data from the programm into the txt file?

---

<div class="post-metadata">

**Author:** ![hsm](https://avatars.discourse-cdn.com/v4/letter/h/ea666f/32.png) [@hsm](https://discourse.processing.org/u/hsm)\
**Post date:** [March 3, 2022, 6:50am UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/4 "2022-03-03T06:50:19Z")

</div>

Did you have a chance to read up about _saveStrings()_?

> **[Reference](https://processing.org/reference/saveStrings_.html)**
>
> Writes an array of Strings to a file, one line per String. By default, this file is saved to the sketch's folder. This folder is opened by selecting "Show Sketch Folder" from the "Sketch" menu. …

---

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 3, 2022, 8:52am UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/5 "2022-03-03T08:52:25Z")

</div>

Thank you. Do you also know how to create a new txt file in the programm code?

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [March 3, 2022, 10:28pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/6 "2022-03-03T22:28:58Z")

</div>

Hi

> **[Reference](https://processing.org/reference/createWriter_.html)**
>
> Creates a new file in the sketch folder, and a PrintWriter object to write to it. For the file to be made correctly, it should be flushed and must be closed with its flush() and close…

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [March 3, 2022, 11:01pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/8 "2022-03-03T23:01:35Z")

</div>

> [@Coder1](#):
>
> Do you also know how to create a new txt file in the programm code?

- You can either use saveStrings() again and write over the existing file (when you load it, add data and save it with the same name, it’s like append data to the existing file, like for a _high score_)

- But you can also generate a new text file. For example just incrementing a number (so file name is myfile1.txt, myfile2.txt…). Or using a file name that is built from date and current time (when you save only once per second maximum).

- There is also a full Save as… dialogue in processing. Here you can enter a file name (like when you save a Sketch in processing).

See reference for all commands.

* * *

**date time stamp for file name**

```auto
  // 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)
    +".txt";

```

* * *

**Save as… dialogue**

see selectOutput() in reference : [Reference / Processing.org](https://processing.org/reference)

it’s [selectOutput() / Reference / Processing.org](https://processing.org/reference/selectOutput_.html)

---

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 4, 2022, 1:11am UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/9 "2022-03-04T01:11:51Z")

</div>

Thank you for the help. Maybe I have forgotten to choose the topic processing for android so it is my fault I apologize. If you know if it works on Android too, it would be great but if you dont then its okay too. Because for some reason it doesn’t work on Android. I get no error but the file doesnt change.

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [March 4, 2022, 8:32am UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/10 "2022-03-04T08:32:37Z")

</div>

Hi

Hi

This example from APDE I just changed the path

```auto
String[] lines;
int index = 0;
String filepath = "/storage/emulated/0/test/positions.txt/";
void setup() {
  size(800, 800);
  background(0);
  stroke(255);
  frameRate(12);
  lines = loadStrings(filepath);

    
}

void draw() {
  if (index < lines.length) {
    String[] pieces = split(lines[index], '\t');
    if (pieces.length == 2) {
      int x = int(pieces[0]) * 2;
      int y = int(pieces[1]) * 2;
      point(x, y);
    }
    // Go to the next line for the next run through draw()
    index = index + 1;
  }
}

```

Read this

> [@Permission issue in reading file from external storage](https://discourse.processing.org/t/permission-issue-in-reading-file-from-external-storage/34184/12):
>
> I tried to work around the path separator issue by using File and Scanner: void loadEnv( String f) { String dir = new String(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+image\_folder+"/"); File file = new File( dir+f); try { println( dir+f); Scanner sc = new Scanner(file); println(sc.next()); } catch (Exception e) { println(e); text("File not found", width/2, height/2); } } Then it returns permission error: java.io.FileNotFoundException: …

---

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 4, 2022, 12:23pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/11 "2022-03-04T12:23:42Z")

</div>

Hello

It says the error that it contains a path separator

---

<div class="post-metadata">

**Author:** ![TimeLex](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/timelex/32/12869_2.png) [@TimeLex](https://discourse.processing.org/u/TimeLex)\
**Post date:** [March 4, 2022, 12:33pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/12 "2022-03-04T12:33:24Z")

</div>

Firstly, your program needs to be converted into an app. If you run it in Notepad, Processing will automatically delete all old files. Second: With Android, apps first have to be authorized to save something. You can use `hasPermission(permissionName)` to test whether your app has the permission. With `requestPermission(permissionName)` you can request permissions. The name of the permission to store data is `android.permission.WRITE_EXTERNAL_STORAGE`.

---

<div class="post-metadata">

**Author:** ![TimeLex](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/timelex/32/12869_2.png) [@TimeLex](https://discourse.processing.org/u/TimeLex)\
**Post date:** [March 4, 2022, 1:06pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/13 "2022-03-04T13:06:52Z")

</div>

I forgot to say that you must enable the permission. Simply go on the 3 points in the top right corner → Sketch Properties → Sketch Permissions and then check `WRITE_EXTERNAL_STORAGE`.

Here is an example:

```auto
boolean maySaveData;

int count = 0;
String countFilePath;

void setup() {
  fullScreen();
  
  countFilePath = dataPath("count.txt");
  
  checkPermission();
  loadAndRequestCount();
}
void loadAndRequestCount() {
  if(maySaveData) {
    checkFileExists(countFilePath, "saveCount");
    loadCount();
  }else{
    requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    checkPermission();
  }
}
void checkPermission() {
  maySaveData = hasPermission("android.permission.WRITE_EXTERNAL_STORAGE");
}
void checkFileExists(String path, String callback) {
  File file = new File(path);
  if(!file.exists())
    method(callback);
}
void saveCount() {
  saveStrings(countFilePath, new String[]{str(count)});
}
int loadCount() {
  count = int(loadStrings(countFilePath)[0]);
  return count;
}

void draw() {
  background(255);
  textAlign(CENTER, CENTER);
  if(maySaveData) {
    textSize(100);
    fill(#000000);
    text(count, width/2, height/2);
  }else{
    textSize(30);
    fill(#FF0000);
    text("Please give permission to save data.\nOtherwise the program can't run correctly.\nPress to request again.", width/2, height/2);
    
    checkPermission();
  }
}

void mousePressed() {
  if(maySaveData) {
    count++;
    saveCount();
  }else
    loadAndRequestCount();
}

```

This code is realy advanced so if you have any qeustions yust ask.  
Hope that helps 😁

---

<div class="post-metadata">

**Author:** ![TimeLex](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/timelex/32/12869_2.png) [@TimeLex](https://discourse.processing.org/u/TimeLex)\
**Post date:** [March 4, 2022, 1:32pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/14 "2022-03-04T13:32:31Z")

</div>

\*Small note:  
I think if you store your files in the dataPath (e.g. `dataPath("count.txt")`) you don’t need to request permission, but I don’t know if some Android devices let you store data only then , if you request this, so do it to be safe.

---

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 4, 2022, 4:24pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/15 "2022-03-04T16:24:22Z")

</div>

Thank you. For me it doesn’t work right. When I start the App then it doesn’t start asking permission and if the permission is already enabled then I get the error “OutOfBoundsException”. But it does work when I replace the filename with something else that doesnt exist. I hope you can help me.

---

<div class="post-metadata">

**Author:** ![TimeLex](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/timelex/32/12869_2.png) [@TimeLex](https://discourse.processing.org/u/TimeLex)\
**Post date:** [March 4, 2022, 8:13pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/16 "2022-03-04T20:13:25Z")

</div>

An `OutOfBoundsException` can only occur if the file is empty. This would also explain why it worked with a different filename (because a new file was created that is not empty). I will change the code again so that this exception cannot be thrown again.

---

<div class="post-metadata">

**Author:** ![TimeLex](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/timelex/32/12869_2.png) [@TimeLex](https://discourse.processing.org/u/TimeLex)\
**Post date:** [March 4, 2022, 8:17pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/17 "2022-03-04T20:17:02Z")

</div>

Try this:

```auto
boolean maySaveData;

int count = 0;
String countFilePath;

void setup() {
  fullScreen();
  
  countFilePath = dataPath("count.txt");
  
  checkPermission();
  loadAndRequestCount();
}
void loadAndRequestCount() {
  if(maySaveData) {
    checkFileExists(countFilePath, "saveCount");
    loadCount();
  }else{
    requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    checkPermission();
  }
}
void checkPermission() {
  maySaveData = hasPermission("android.permission.WRITE_EXTERNAL_STORAGE");
}
void checkFileExists(String path, String callback) {
  File file = new File(path);
  if(!file.exists())
    method(callback);
  else if(loadStrings(path).length == 0)
    saveCount();
}
void saveCount() {
  saveStrings(countFilePath, new String[]{str(count)});
}
int loadCount() {
  count = int(loadStrings(countFilePath)[0]);
  return count;
}

void draw() {
  background(255);
  textAlign(CENTER, CENTER);
  if(maySaveData) {
    textSize(100);
    fill(#000000);
    text(count, width/2, height/2);
  }else{
    textSize(30);
    fill(#FF0000);
    text("Please give permission to save data.\nOtherwise the program can't run correctly.\nPress to request again.", width/2, height/2);
    
    checkPermission();
  }
}

void mousePressed() {
  if(maySaveData) {
    count++;
    saveCount();
  }else
    loadAndRequestCount();
}

```

---

<div class="post-metadata">

**Author:** ![Coder1](https://avatars.discourse-cdn.com/v4/letter/c/d9b06d/32.png) [@Coder1](https://discourse.processing.org/u/Coder1)\
**Post date:** [March 4, 2022, 10:08pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/18 "2022-03-04T22:08:04Z")

</div>

Thanks. But for some reason I dont get the request to access the write external storage thing anymore

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [March 4, 2022, 11:40pm UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/19 "2022-03-04T23:40:51Z")

</div>

Hi

Permission given just once and requested just once @TimeLex sketch is working you have to select your path

```auto
boolean maySaveData;

int count = 0;
String countFilePath;

void setup() {
  fullScreen();
  
 
 countFilePath = "/storage/emulated/0/conunt.txt/";
  checkPermission();
  loadAndRequestCount();
}
void loadAndRequestCount() {
  if(maySaveData) {
    checkFileExists(countFilePath, "saveCount");
    loadCount();
  }else{
    requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    checkPermission();
  }
}
void checkPermission() {
  maySaveData = hasPermission("android.permission.WRITE_EXTERNAL_STORAGE");
}
void checkFileExists(String path, String callback) {
  File file = new File(path);
  if(!file.exists())
    method(callback);
  else if(loadStrings(path).length == 0)
    saveCount();
}
void saveCount() {
  saveStrings(countFilePath, new String[]{str(count)});
}
int loadCount() {
  count = int(loadStrings(countFilePath)[0]);
  return count;
}

void draw() {
  background(255);
  textAlign(CENTER, CENTER);
  if(maySaveData) {
    textSize(100);
    fill(#000000);
    text(count, width/2, height/2);
  }else{
    textSize(30);
    fill(#FF0000);
    text("Please give permission to save data.\nOtherwise the program can't run correctly.\nPress to request again.", width/2, height/2);
    
    checkPermission();
  }
}

void mousePressed() {
  if(maySaveData) {
    count++;
    saveCount();
  }else
    loadAndRequestCount();
}

```

 ![Screenshot_2022-03-05-01-09-05-305](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/a/a68d9ad7685b5f5bd820313d65a83eb1ef8ea17a.jpeg)  
 ![Screenshot_2022-03-05-01-07-15-678](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/5/581d03d336a24307d9f76251151193fe1b68d93d.jpeg)  
 ![Screenshot_2022-03-05-01-30-22-644](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/4/43c683b51a13fb37be3b073ae34430e442004b01.jpeg)

---

<div class="post-metadata">

**Author:** ![PhoenixStormJr](https://avatars.discourse-cdn.com/v4/letter/p/43a26b/32.png) [@PhoenixStormJr](https://discourse.processing.org/u/PhoenixStormJr)\
**Post date:** [March 10, 2022, 12:11am UTC](https://discourse.processing.org/t/how-to-save-data-in-a-program/35525/21 "2022-03-10T00:11:44Z")

</div>

Or this would be a better link

> [@Read and write images and text files Android](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947):
>
> text saver. Save text to any location in android. Please set the manifest permissions by adding the following file to your sketch folder. AndroidManifest.xml \<?xml version="1.0" encoding="UTF-8"?\> \<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package=""\> \<uses-sdk android:minSdkVersion="17" android:targetSdkVersion="28"/\> \<application android:icon="@mipmap/ic\_launcher" android:label=""\> \<activity android:n…
