# Read and write images and text files Android

**URL:** <https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947>\
**Category:** Gallery\
**Created:** [May 7, 2021, 5:16pm UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947 "2021-05-07T17:16:53Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [May 7, 2021, 5:16pm UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/1 "2021-05-07T17:16:55Z")

</div>

text saver. Save text to any location in android. Please set the manifest permissions by adding the following file to your sketch folder.

```auto
AndroidManifest.xml

```

```auto
<?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:name=".MainActivity" android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

```

```auto
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;

Activity activity; 
Context context; 
Permission p;
String s1 ,s2 = "iuiugifuy";
String absolutePath;
public boolean overWrite = true;

public void setup(){
  size(600,600);
  p = new Permission(this,"WRITE_EXTERNAL_STORAGE");
  activity = this.getActivity(); 
  context = activity.getApplicationContext();
  absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath()); 
  
};

public void draw(){
  background(255);
  
  
  if(s1!=null){
    fill(0);
    text(s1,20,20);
  }else{
    fill(0);
    text("no file",20,20);
  }
  
};

void mousePressed(){
  generateNoteOnSD(context,"test.txt",s2+hour()+":"+minute()+":"+second());
  readFromFile(context);
};

public void generateNoteOnSD(Context context, String FileName, String text) {
  try {
    //
      File root = new File(absolutePath, "Notes");
      if (!root.exists()) {
          root.mkdirs();
      }
      File gpxfile = new File(root, FileName);
      //set to false will overwrite the file, set to true to append
      FileWriter writer = new FileWriter(gpxfile,false);
      //use write or append
      writer.append(text);
      // use \n to add new line
      writer.append("\n");
      
      writer.flush();
      writer.close();
      println("write file");
  } catch (IOException e) {
      e.printStackTrace();
  }
};

  
private String readFromFile(Context context) {

    FileInputStream fis = null;
    try {

        fis = new FileInputStream (new File(absolutePath+"/notes/"+"test.txt"));
        InputStreamReader isr = new InputStreamReader(fis);
        // READ STRING OF UNKNOWN LENGTH
        StringBuilder sb = new StringBuilder();
        char[] inputBuffer = new char[2048];
        int l;
        // FILL BUFFER WITH DATA
        while ((l = isr.read(inputBuffer)) != -1) {
            sb.append(inputBuffer, 0, l);
            println("write data",inputBuffer, 0, l);
        }
        // CONVERT BYTES TO STRING
        s1 = sb.toString();
        
        fis.close();

    }catch (Exception e) {
      println("cannot fetch file",e);
    } finally {
        if (fis != null) {
            
            fis = null;
        }
    }
    return s1;
};

```

image saver. Save image to any location in android.

```auto
import android.os.Environment;
import android.Manifest; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.os.Build.VERSION_CODES; 
import processing.core.PConstants;
import android.app.Activity; 

PImage img;
Activity activity; 
boolean image_saved;
boolean permissions_granted;

// Folowing file name is the folder you save your image file in.
// If it does not exist it will be created automatically
String folder_name = "MyImageFolder";

// Folowing string is the name of your image file
// Be sure to include extension.
String image_file = "MyImage.jpg";
Permission wstorage,rstorage;
void setup() {
  wstorage = new Permission(this,"WRITE_EXTERNAL_STORAGE");
  rstorage = new Permission(this,"READ_EXTERNAL_STORAGE");
  size(displayWidth, displayHeight);
  background(0, 0, 200); 
  rectMode(CENTER);
  rect(width/2, height/2, width, height/2);
  textAlign(CENTER);
  String str = "Click to save an image.";
  textSize(12);
  float twf = width/textWidth(str);
  textSize(8*twf);
  fill(0);
  text(str, width/2, height/2);
  img = get();
  //img.save(
};

void draw() {
  if (image_saved) {
    background(0, 0, 200);
    fill(255);
    text("Image saved.", width/2, height/2);
  } 
};

void mousePressed() {
  saveMyImage(folder_name, image_file);
};

void saveMyImage(String sf, String tf) { 
  try { 
    String absolute_path = new String(Environment.getExternalStorageDirectory().getAbsolutePath()); 
    File file = new File(absolute_path+"/"+sf); 
    //println(file);
    if (!file.exists()) { 
      boolean success = true; 
      success = file.mkdirs();
      if(success){
        save(file+"/"+tf);
        image_saved = true;
        println("File saved successfully.");
        println("Path",absolute_path,"File",file);
      }
      else {
        println("no File");
        println("Path",absolute_path,"File",file);
      }
    } 
    
    
  } 
  catch (Exception e) { 
    //println("Error while saving file: " + e);
  }
};

```

image saver as a class if image with a matching filename is found the file is then numbered before saving;

```auto
import android.os.Environment;
import android.Manifest; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.os.Build.VERSION_CODES; 

import android.app.Activity; 
imageSaver img;

void setup(){
  size(displayWidth, displayHeight);
  background(0, 0, 200); 
  rectMode(CENTER);
  rect(width/2, height/2, width, height/2);
  textAlign(CENTER);
  String str = "Click to save an image.";
  textSize(12);
  float twf = width/textWidth(str);
  textSize(8*twf);
  fill(0);
  text(str, width/2, height/2);
  img = new imageSaver(this);
};

void draw(){
  img.logic();
};

```

```auto
class imageSaver{
  Permission wstorage,rstorage;
  Activity act;
  PApplet p;
  int counter = -1,maxImageCount;
  boolean imageSaved,mdown;
  String folderName = "MyImageFolder",fileName,ext,absolutePath;
  String imageFile = "MyImage.jpg";
  PImage img;
  File file,file2;
  
  imageSaver(PApplet applet){
    p = applet;
    wstorage = new Permission(p,"WRITE_EXTERNAL_STORAGE");
    act = p.getActivity();
    getExt(imageFile);
  };
  
  imageSaver(PApplet applet,String s1, String s2){
    folderName = s1;
    imageFile = s2;
    p = applet;
    wstorage = new Permission(p,"WRITE_EXTERNAL_STORAGE");
    act = p.getActivity();
    getExt(imageFile);
  };
  
  public void logic() {
    if(mousePressed&&!mdown) {
      img = p.get();
      checkLocation(folderName, imageFile);
      mdown = true;
      counter++;
    }
    if(!mousePressed)mdown = false;
  };

  public void logic(PGraphics canvas) {
    if(true) {
      
      img = canvas.get();
      checkLocation(folderName, imageFile);
      counter++;
    }
  };

  public void checkLocation(String sf, String tf) { 
    boolean k = false;
    try { 
      absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath()); 
      file = new File(absolutePath+"/"+sf); 
      //PApplet.println("checking file1",file,counter);
      if (!file.exists()&&counter==-1) { 
        boolean success = true; 
        success = file.mkdirs();
        img.save(file+"/"+fileName+"."+ext);
        
      } else k = true;
      
      if(counter>-1)k=true;
      boolean k1 = false;
      while(k&&counter<100&&!k1) {
        try { 
          file2 = new File(absolutePath+"/"+folderName+"/"+fileName+counter+"."+ext); 
          PApplet.println("checking file2",file2);
          if (file2.exists()) { 
            counter++;
          } else {
            k = false;
            k1 = true;
            break;
          }
        } 
        catch (Exception e) { 
          PApplet.println("Error while saving file: " + e);
        }
      }
      if(k1){
        //PApplet.println("file",file);
        //PApplet.println("Fname",folderName);
        //PApplet.println("fileName",fileName);
        //PApplet.println("counter",counter);
        //PApplet.println("ext",ext);
        if(counter>-1)img.save(file+"/"+fileName+counter+"."+ext);
        imageSaved = true;
        //PApplet.println("File saved successfully.");
      }
    } 
    catch (Exception e) { 
      PApplet.println("Error while saving file: " + e);
    }
  };
  
  void getExt(String location){

    int count = 0;
    fileName = location.substring(0,location.indexOf("."));
    ext = location.replace(fileName,"");
    ext = ext.replace(".","");
    ext = ext.replace(fileName,"");
  };
  
  public File[] listFiles(String dir) {
    File file = new File(dir);
    if (file.isDirectory()) {
      File[] files = file.listFiles();
      return files;
    } else {
      // If it's not a directory
      return null;
    }
  };

};

```

```auto
public class Permission{
  
  String permissionName;
  PApplet parent;

  public Permission(PApplet pParent,String permissionName) {
    parent = pParent;
    this.permissionName = permissionName;
    parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
  };

  public void onPermissionResult(boolean granted) {
    if (!granted) {
      PApplet.println("User did not grant camera permission. "+ permissionName +" is disabled.");
    }
  };

};

```

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [May 9, 2021, 11:33pm UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/2 "2021-05-09T23:33:43Z")

</div>

text reader writer as a class. Write anywhere in any folder.

you can set the file to overwrite and or append, not sure if overWriteFirst is necessary. But everything works.

just make sure to call `close()` after writing, other wise move the close method into the write methods.

```auto
setLocation();

```

this will populate the folderPath, fileName and ext of the file.  
there is then a counter currently set to a maximum of 100 files. This is to increment up if a file with the matching filename is found based on the starting params you have chosen.

Overwrite will simply overWrite any file of the same name and keep saving to that same location.

```auto
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
FileOutput f;
String s1 ,s2 = "iuiugifuy";

public void setup(){
  size(600,600);
  
  f = new FileOutput(this);
  f.setLocation("notes/test.txt");
  f.checkLocation();
};

public void draw(){
  background(255);
  
  
  if(f.fileContent!=null){
    fill(0);
    text(f.fileContent,20,20);
  }else{
    fill(0);
    text("no file",20,20);
  }
  
};

void mousePressed(){
  f.writeLn(s2+hour()+":"+minute()+":"+second());
  f.close();
  f.loadStrings();
};
 

```

```auto
class FileOutput {
  public PApplet applet;
  public FileWriter output;
  public boolean save, onMouseUp, mdown, debug, append = true, appendFile, match, append2, overWrite = true, overWriteOnce = true,writeOnce;
  public int counter=-1, counter2;
  public File file, file2;
  public File[] SDcards ; 
  public String location, filePath, folderPath = "";
  String text = "oioijsofoivnsoindv", absolutePath, ext, fileName,fileContent = "";
  Permission p;
  Activity activity;
  Context context;

  FileOutput() {
    
  };

  FileOutput(boolean a, PApplet app) {

    applet = app;
    p = new Permission(app,"WRITE_EXTERNAL_STORAGE");
    overWrite = true;
    appendFile = true;
  };

  FileOutput(PApplet app) {

    applet = app;
    p = new Permission(app,"WRITE_EXTERNAL_STORAGE");
  };
  //currently unused
  FileOutput(String location, PApplet app) {

    applet = app;
    p = new Permission(app,"WRITE_EXTERNAL_STORAGE");
    setLocation(location);
  };

  FileOutput(PApplet app, String location) {

    applet = app;
    p = new Permission(app,"WRITE_EXTERNAL_STORAGE");
    setLocation(location);
  };

  public void getAndroidInfo() {
    activity = applet.getActivity(); 
    context = activity.getApplicationContext();
    absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
  };

  void loadStrings() {
    loadFile(context);
  };

  String loadFile(Context context) {

    FileInputStream fis = null;
    try {
      fis = new FileInputStream (new File(file2.getAbsolutePath()));
      InputStreamReader isr = new InputStreamReader(fis);
      // READ STRING OF UNKNOWN LENGTH
      StringBuilder sb = new StringBuilder();
      char[] inputBuffer = new char[2048];
      int l;
      // FILL BUFFER WITH DATA
      while ((l = isr.read(inputBuffer)) != -1) {
        sb.append(inputBuffer, 0, l);
        println("write data", inputBuffer, 0, l);
      }
      // CONVERT BYTES TO STRING
      fileContent = sb.toString();

      fis.close();
    }
    catch (Exception e) {
      println("cannot fetch file", e);
    } 
    finally {
      if (fis != null) {

        fis = null;
      }
    }
    return fileContent;
  };

  void open() {
  };

  void close() {
    try {
      output.flush();
      output.close();
    }
    catch(IOException e) {
    }
  };

  void write(String s) {
    
    if(!overWrite)checkLocation();
    try {
      
      output = new FileWriter(file2, append);
    }
    catch(IOException e) {
    }
    printWrite(s);
  };

  void writeLn(String s) {
    if(!overWrite)checkLocation();
    try {
      output = new FileWriter(file2, append);
    }
    catch(IOException e) {
    }
    printWriteLn(s);
  };

  void write(String []s) {
    if(!overWrite)checkLocation();
    try {
      output = new FileWriter(file2, append);
    }
    catch(IOException e) {
    }
    printWrite(s);
  };
  
  void writeLn(String []s) {
    if(!overWrite)checkLocation();
    try {
      output = new FileWriter(file2, append);
    }
    catch(IOException e) {
    }
    printWriteLn(s);
  };

  void printWrite(String s) {
    if(!overWrite)checkLocation();
    try {
      output.append(s);
    }
    catch(IOException e) {
    }
  };

  void printWriteLn(String s) {
    if(!overWrite)checkLocation();
    try {
      output.append(s);
      output.append("\n");
    }
    catch(IOException e) {
    }
  };
  
  void printWrite(String []s) {
    if(!overWrite)checkLocation();
    try {
      for(int i=0;i<s.length;i++){
        output.append(s[i]);
      }
    }
    catch(IOException e) {
    }
  };

  void printWriteLn(String []s) {
    if(!overWrite)checkLocation();
    try {
      for(int i=0;i<s.length;i++){
        output.append(s[i]);
        output.append("\n");
      }
      
    }
    catch(IOException e) {
    }
  };

  void checkLocation() {
    boolean k = false;
    try {
      //
      file = new File(absolutePath, folderPath);
      if (!file.exists()&&counter==-1) {
        file.mkdirs();
        file2 = new File(file, "/"+fileName+"."+ext);
        PApplet.println("checking file1", file2);
        if (file2.exists()) {
          counter ++;
        }
      } else k = true;

      if (overWrite&&writeOnce){
        k=false;
        
      }else if(overWrite&&!writeOnce){
        writeOnce = true;
        k = true;
      }
      boolean k1 = false;
      while (k&&counter<100&&!k1) {
        try { 
          file2 = new File(absolutePath+"/"+folderPath+"/"+fileName+counter+"."+ext); 
          
          if (file2.exists()) { 
            counter++;
          } else {
            PApplet.println("checking file2", file2);
            //output = new FileWriter(file2, append);
            k = false;
            k1 = true;
            break;
          }
        } 
        catch (Exception e) { 
          PApplet.println("Error while saving file: " + e);
        }
      }
      if (overWriteOnce)overWriteOnce = false;
      if (k1) {
        //PApplet.println("file",file);
        //PApplet.println("Fname",folderName);
        //PApplet.println("fileName",fileName);
        //PApplet.println("counter",counter);
        //PApplet.println("ext",ext);
        if (file2==null&&counter<0)file2 = new File(absolutePath+"/"+folderPath+"/"+fileName+"."+ext); 
        else if(file2==null)file2 = new File(absolutePath+"/"+folderPath+"/"+fileName+"."+ext); 
        if (counter==-1) {
          //img.save(file+"/"+fileName+counter+"."+ext);
          
          output = new FileWriter(file2, append);
          //use write or append
        }
        //PApplet.println("File saved successfully.");
      }
      println("write file", folderPath, fileName,counter, ext);
    } 
    catch (IOException e) {
      e.printStackTrace();
    }
  };

  void setLocation(String s) {
    getAndroidInfo();
    location = s;
    folderPath = s.substring(0, s.lastIndexOf("/"));
    fileName = s.replace(folderPath+"/", "");
    getExt(fileName);
    PApplet.println("Fname", folderPath);
    PApplet.println("fileName", fileName);
    PApplet.println("counter", counter);
    PApplet.println("ext", ext);
  }

  void getExt(String location) {

    int count = 0;
    fileName = location.substring(0, location.indexOf("."));
    ext = location.replace(fileName, "");
    ext = ext.replace(".", "");
    ext = ext.replace(fileName, "");
  };
};

```

```auto
public class Permission{
  
  PApplet parent;
  String p;

  public Permission(PApplet pParent,String permissionName) {
    p = permissionName;
    parent = pParent;
    parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
    println(permissionName);
  };

  public void onPermissionResult(boolean granted) {
    if (!granted) {
      PApplet.println("User did not grant camera permission.",p,"is disabled.");
    }
  };

};

```

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [May 12, 2021, 8:16pm UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/3 "2021-05-12T20:16:37Z")

</div>

now updated with gui.

main class bms dependant

> **Summary**
>
> ```auto
> class FileOutput2 {
> BMScontrols Bms;
> public PApplet applet;
> public FileWriter output;
> float x, y, w, h;
> public boolean save, onMouseUp, mdown, debug, append = true, appendFile, match, 
> append2, overWrite = true, overWriteOnce = true, writeOnce, writeFile, click, 
> getPermission = true, fileExists, reWrite;
> public int counter=-1, counter2;
> public File file, file2, file3;
> public File[] SDcards ; 
> public String location, filePath, folderPath = "";
> String text = "oioijsofoivnsoindv", absolutePath, ext, fileName, fileContent = "";
> String androidDialogueTitle = "Would you like to overWrite",
> dialogueB1Title = "",dialogueB2Title = "",dialogueBody;
> Permission p;
> Activity activity;
> Context context;
> dialogueBox dbox; 
> TextView msg;
> int msgId;
> 
> FileOutput2() {
> };
> 
> FileOutput2(boolean a, BMScontrols bms) {
> Bms = bms;
> applet = bms.applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> overWrite = true;
> appendFile = true;
> };
> 
> FileOutput2(BMScontrols bms) {
> Bms = bms;
> applet = bms.applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> //init();
> };
> //currently unused
> FileOutput2(String location, BMScontrols bms) {
> Bms = bms;
> applet = bms.applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> setLocation(location);
> init();
> };
> 
> FileOutput2(BMScontrols bms, String location) {
> Bms = bms;
> applet = bms.applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> setLocation(location);
> init();
> };
> 
> void getAndroidInfo() {
> activity = applet.getActivity(); 
> context = activity.getApplicationContext();
> absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
> };
> 
> void init() {
> x = 0;
> y = 0;
> w = applet.width;
> h = applet.height;
> 
> String s1 = "Would you like to overWrite "+fileName+"."+ext+"?";
> float dboxWidth = 120;
> float tSize = 20;
> applet.textSize(tSize);
> float dw = applet.textWidth(s1)+100;
> float dboxHeight = 150;
> float dx = applet.width/2-dw/2;
> float dy = applet.height/2-50/2;
> 
> dbox = new dialogueBox(dx, dy, dw, dboxHeight, s1, bms);
> dbox.$ok(10, 20, dbox.main.w/2-20, dbox.main.h-60, "Yes");
> dbox.$no(dbox.main.w/2+10, 20, dbox.main.w/2-20, dbox.main.h-60, "No");
> dbox.main.setTextSize(tSize);
> dbox.main.setRadius(10);
> };
> 
> void loadStrings() {
> loadFile(context);
> };
> 
> String loadFile(Context context) {
> 
> FileInputStream fis = null;
> if (writeFile) {
> try {
> if (!reWrite)fis = new FileInputStream (new File(file2.getAbsolutePath()));
> else fis = new FileInputStream (new File(file3.getAbsolutePath()));
>         
> InputStreamReader isr = new InputStreamReader(fis);
> // READ STRING OF UNKNOWN LENGTH
> StringBuilder sb = new StringBuilder();
> char[] inputBuffer = new char[2048];
> int l;
> // FILL BUFFER WITH DATA
> while ((l = isr.read(inputBuffer)) != -1) {
> sb.append(inputBuffer, 0, l);
> println("write data", inputBuffer, 0, l);
> }
> // CONVERT BYTES TO STRING
> fileContent = sb.toString();
> 
> fis.close();
> }
> catch (Exception e) {
> println("cannot fetch file", e);
> } 
> finally {
> if (fis != null) {
> 
> fis = null;
> }
> }
> }
> return fileContent;
> };
> 
> void open() {
> };
> 
> void close() {
> try {
> output.flush();
> output.close();
> }
> catch(IOException e) {
> }
> };
> 
> void write(String s) {
> 
> if (!overWrite)checkLocation();
> try {
> 
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWrite(s);
> };
> 
> void writeLn(String s) {
> if (!overWrite)checkLocation();
> try {
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWriteLn(s);
> };
> 
> void write(String []s) {
> if (!overWrite)checkLocation();
> try {
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWrite(s);
> };
> 
> void writeLn(String []s) {
> if (!overWrite)checkLocation();
> try {
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWriteLn(s);
> };
> 
> void printWrite(String s) {
> if (!overWrite)checkLocation();
> try {
> output.append(s);
> }
> catch(IOException e) {
> }
> };
> 
> void printWriteLn(String s) {
> if (!overWrite)checkLocation();
> try {
> output.append(s);
> output.append("\n");
> }
> catch(IOException e) {
> }
> };
> 
> void printWrite(String []s) {
> if (!overWrite)checkLocation();
> try {
> for (int i=0; i<s.length; i++) {
> output.append(s[i]);
> }
> }
> catch(IOException e) {
> }
> };
> 
> void printWriteLn(String []s) {
> if (!overWrite)checkLocation();
> try {
> for (int i=0; i<s.length; i++) {
> output.append(s[i]);
> output.append("\n");
> }
> }
> catch(IOException e) {
> }
> };
> 
> void checkLocation() {
> boolean k = false;
> String s1 = "Would you like to overWrite "+fileName+counter+"."+ext+"?";
> try {
> //
> file = new File(absolutePath, folderPath);
> if (!file.exists()&&counter==-1) {
> file.mkdirs();
> file2 = new File(file, "/"+fileName+"."+ext);
> androidDialogueTitle = file.getAbsolutePath();
> PApplet.println("checking file1", file2);
> if (file2.exists()) {
> counter ++;
> 
> PApplet.println("File Exists");
> //dbox.main.title.label = s1;
> }
> } else if (counter==-1) {
> fileExists = true;
> counter = 0;
> k = true;
> } else k = true;
> if (overWrite&&writeOnce) {
> k=false;
> } else if (overWrite&&!writeOnce&&writeFile) {
> writeOnce = true;
> k = true;
> }
> boolean k1 = false;
> if (writeFile)
> while (k&&counter<100&&!k1) {
> s1 = fileName+counter+"."+ext+"?";
> try { 
> 
> file2 = new File(absolutePath+"/"+folderPath+"/"+fileName+counter+"."+ext);
> file3 = new File(absolutePath+"/"+folderPath+"/"+fileName+(counter)+"."+ext);
> androidDialogueTitle = file3.getAbsolutePath();
> if (file2.exists()) { 
> counter++;
> } else {
> PApplet.println("checking file2", file2);
> //output = new FileWriter(file2, append);
> k = false;
> k1 = true;
> break;
> }
> } 
> catch (Exception e) { 
> PApplet.println("Error while saving file: " + e);
> }
> }
> if (k1||!writeFile) {
> //PApplet.println("file",file);
> //PApplet.println("Fname",folderName);
> //PApplet.println("fileName",fileName);
> //PApplet.println("counter",counter);
> //PApplet.println("ext",ext);
> if (file2==null&&counter<0)file2 = new File(file+"/"+fileName+"."+ext); 
> else if (file2==null)file2 = new File(file+"/"+fileName+"."+ext); 
> if (output==null) {
> //img.save(file+"/"+fileName+counter+"."+ext);
> 
> if (writeFile)output = new FileWriter(file2, append);
> PApplet.println("File saved successfully.");
> //use write or append
> }
> }
> if (reWrite) {
> file2 = new File(file+"/"+fileName+counter+"."+ext); 
> output = new FileWriter(file2, append);
> }
> println("write file", folderPath, fileName, counter, ext);
> if (reWrite)overWrite = true;
> } 
> catch (IOException e) {
> e.printStackTrace();
> }
> };
> 
> void listen() {
> //if(writeFile&&dbox.main.getButton(0).click)checkLocation();
> };
> 
> void setLocation(String s) {
> if (getPermission)getAndroidInfo();
> location = s;
> folderPath = s.substring(0, s.lastIndexOf("/"));
> fileName = s.replace(folderPath+"/", "");
> getExt(fileName);
> PApplet.println("Fname", folderPath);
> PApplet.println("fileName", fileName);
> PApplet.println("counter", counter);
> PApplet.println("ext", ext);
> checkLocation();
> init();
> }
> 
> void getExt(String location) {
> 
> int count = 0;
> fileName = location.substring(0, location.indexOf("."));
> ext = location.replace(fileName, "");
> ext = ext.replace(".", "");
> ext = ext.replace(fileName, "");
> };
> 
> void drawDialogue() {
> fill(0, 100);
> if(!writeFile)rect(0, 0, applet.width, applet.height);
> String s1 = "Would you like to save "+'"'+fileName+"."+ext+'"'+ "?";
> if (!fileExists)dbox.main.title.label = s1;
>     
> if (getPermission) {
> dbox.draw();
> 
> if (dbox.main.toggle(0, this, "writeFile"))overWrite = true;
> if (dbox.main.toggle(1, this, "writeFile")) {
> overWrite = false;
> reWrite = true;
> }
> //if(dbox.main.toggle(0)){
> // println("fout drawd");
> // writeFile = true;
> 
> //}
> if (writeFile)getPermission = false;
> }
> };
> 
> void dialogBox() {
> 
> msg = new TextView(activity); 
> msg.setBackgroundColor(Color.BLUE);
> msg.setTextSize(32);
> msg.setText(dialogueBody); 
> msg.setGravity(Gravity.CENTER_HORIZONTAL); 
> msg.setTextColor(Color.WHITE); 
> 
> activity.runOnUiThread(new Runnable() {
> public void run() {
> AlertDialog.Builder builder = new AlertDialog.Builder(activity);
> builder.setView(msg);
>         
> androidDialogueTitle += " "+fileName+"."+ext+"?";
> builder.setTitle(androidDialogueTitle);
> builder.setPositiveButton(dialogueB1Title, 
> new DialogInterface.OnClickListener() {
> public void onClick(DialogInterface dialog, 
> int which) {
> writeFile = true;
> overWrite = false;
> reWrite = true;
>               
> }
> }
> );
> builder.setNegativeButton(dialogueB2Title, 
> new DialogInterface.OnClickListener() {
> public void onClick(DialogInterface dialog, 
> int which) {
> writeFile = true;
> overWrite = true;
> //act.finish();
> }
> }
> )
> .show();
> }
> }
> );
> };
>   
> void setAndroidDialogue(String s1,String s2){
> dialogueB1Title = s1;
> dialogueB2Title = s2;
>     
> };
>   
> void setAndroidDialogue(String s1,String s2,String s3){
> androidDialogueTitle = s1;
> dialogueB1Title = s2;
> dialogueB2Title = s3;
>     
> };
>   
> void setAndroidDialogueTitle(String s1){
> androidDialogueTitle = s1;
> };
>   
> void setDialogueColor(){
>     
> };
> 
> public boolean click() {
> boolean k = false;
> if (pos()&&applet.mousePressed&&!click) {
> click = true;
> k = false;
> } else if (click&&!applet.mousePressed) {
> k = true;
> click = false;
> }
> return k;
> };
> 
> public boolean pos(PVector mouse) {
> return mouse.x>x&&mouse.x<x+w&&mouse.y>y&&mouse.y<y+h;
> };
> 
> public boolean pos() {
> return applet.mouseX>x&&applet.mouseX<x+w&&applet.mouseY>y&&applet.mouseY<y+h;
> };
> };
> 
> ```

sketch

> **Summary**
>
> ```auto
> import java.io.BufferedReader;
> import java.io.BufferedWriter;
> import java.io.File;
> import java.io.FileInputStream;
> import java.io.FileNotFoundException;
> import java.io.FileOutputStream;
> import java.io.FileReader;
> import java.io.FileWriter;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.io.OutputStreamWriter;
> import java.io.PrintWriter;
> 
> import android.app.Activity;
> import android.content.Context;
> import android.os.Environment;
> import android.content.DialogInterface;
> import android.graphics.Color;
> import android.widget.TextView;
> import android.view.Gravity;
> import processing.core.PApplet;
> import android.app.Activity;
> import android.app.AlertDialog;
> 
> FileOutput2 f;
> BMScontrols bms;
> 
> String s2 = "oifoifnowibf";
> void settings() {
> size(600, 600, P2D);
> };
> 
> public void setup() {
> 
> bms = new BMScontrols(this, true, true);
> f = new FileOutput2(bms);
> f.setLocation("notes/test.txt");
> f.setAndroidDialogue("No","Yessss");
> };
> 
> public void draw() {
> background(255);
> //uncomment if using built in android dialogue
> f.drawDialogue();
> //comment if using built in android dialogue
> //f.dialogBox();
> if (f.fileContent!=null) {
> fill(0);
> text(f.counter, 20, 10);
> text(f.fileContent, 20, 20);
> } else {
> fill(0);
> text("no file", 20, 20);
> }
> };
> 
> void mousePressed() {
> if (f.writeFile) {
> f.writeLn(s2+hour()+":"+minute()+":"+second());
> f.close();
> f.loadStrings();
> }
> //uncomment to access android built in dialogue
> //if(!f.writeFile)f.dialogBox();
> };
> 
> ```

Using my own custom lib.

 ![Screenshot_20210512_211517_processing.test.writetxtfile](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/a/a62dc3816688741dd367ab96d9853f31a4993448.jpeg)

using the android Built in Dialogue Box Class

 ![Screenshot_20210512_211733_processing.test.writetxtfile](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/0/0780d0cbd3d7e2972cc14c5105a2288e7947548c.jpeg)

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [May 13, 2021, 1:06am UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/4 "2021-05-13T01:06:33Z")

</div>

main class non Bms lib dependent;

> **Summary**
>
> ```auto
> class fileOutput {
> public PApplet applet;
> public FileWriter output;
> float x, y, w, h;
> public boolean save, onMouseUp, mdown, debug, append = true, appendFile, match, 
> append2, overWrite = true, overWriteOnce = true, writeOnce, writeFile, click, 
> getPermission = true, fileExists, reWrite;
> public int counter=-1, counter2;
> public File file, file2, file3;
> public File[] SDcards ; 
> public String location, filePath, folderPath = "";
> String text = "oioijsofoivnsoindv", absolutePath, ext, fileName, fileContent = "";
> String androidDialogueTitle = "Would you like to overWrite",
> dialogueB1Title = "",dialogueB2Title = "",dialogueBody;
> Permission p;
> Activity activity;
> Context context;
> TextView msg;
> int msgId;
> 
> fileOutput() {
> };
> 
> fileOutput(boolean a, PApplet applet) {
>     
> this.applet = applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> overWrite = true;
> appendFile = true;
> };
> 
> fileOutput(PApplet app) {
> applet = app;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> //init();
> };
> //currently unused
> fileOutput(String location, PApplet applet) {
>     
> this.applet = applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> setLocation(location);
> init();
> };
> 
> fileOutput(PApplet applet, String location) {
>     
> this.applet = applet;
> p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
> setLocation(location);
> init();
> };
> 
> void getAndroidInfo() {
> activity = applet.getActivity(); 
> context = activity.getApplicationContext();
> absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
> };
> 
> void init() {
> x = 0;
> y = 0;
> w = applet.width;
> h = applet.height;
> 
> String s1 = "Would you like to overWrite "+fileName+"."+ext+"?";
> float dboxWidth = 120;
> float tSize = 20;
> applet.textSize(tSize);
> float dw = applet.textWidth(s1)+100;
> float dboxHeight = 150;
> float dx = applet.width/2-dw/2;
> float dy = applet.height/2-50/2;
> };
> 
> void loadStrings() {
> loadFile(context);
> };
> 
> String loadFile(Context context) {
> 
> FileInputStream fis = null;
> if (writeFile) {
> try {
> if (!reWrite)fis = new FileInputStream (new File(file2.getAbsolutePath()));
> else fis = new FileInputStream (new File(file3.getAbsolutePath()));
>         
> InputStreamReader isr = new InputStreamReader(fis);
> // READ STRING OF UNKNOWN LENGTH
> StringBuilder sb = new StringBuilder();
> char[] inputBuffer = new char[2048];
> int l;
> // FILL BUFFER WITH DATA
> while ((l = isr.read(inputBuffer)) != -1) {
> sb.append(inputBuffer, 0, l);
> println("write data", inputBuffer, 0, l);
> }
> // CONVERT BYTES TO STRING
> fileContent = sb.toString();
> 
> fis.close();
> }
> catch (Exception e) {
> println("cannot fetch file", e);
> } 
> finally {
> if (fis != null) {
> 
> fis = null;
> }
> }
> }
> return fileContent;
> };
> 
> void open() {
> };
> 
> void close() {
> try {
> output.flush();
> output.close();
> }
> catch(IOException e) {
> }
> };
> 
> void write(String s) {
> 
> if (!overWrite)checkLocation();
> try {
> 
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWrite(s);
> };
> 
> void writeLn(String s) {
> if (!overWrite)checkLocation();
> try {
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWriteLn(s);
> };
> 
> void write(String []s) {
> if (!overWrite)checkLocation();
> try {
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWrite(s);
> };
> 
> void writeLn(String []s) {
> if (!overWrite)checkLocation();
> try {
> output = new FileWriter(file2, append);
> }
> catch(IOException e) {
> }
> printWriteLn(s);
> };
> 
> void printWrite(String s) {
> if (!overWrite)checkLocation();
> try {
> output.append(s);
> }
> catch(IOException e) {
> }
> };
> 
> void printWriteLn(String s) {
> if (!overWrite)checkLocation();
> try {
> output.append(s);
> output.append("\n");
> }
> catch(IOException e) {
> }
> };
> 
> void printWrite(String []s) {
> if (!overWrite)checkLocation();
> try {
> for (int i=0; i<s.length; i++) {
> output.append(s[i]);
> }
> }
> catch(IOException e) {
> }
> };
> 
> void printWriteLn(String []s) {
> if (!overWrite)checkLocation();
> try {
> for (int i=0; i<s.length; i++) {
> output.append(s[i]);
> output.append("\n");
> }
> }
> catch(IOException e) {
> }
> };
> 
> void checkLocation() {
> boolean k = false;
> String s1 = "Would you like to overWrite "+fileName+counter+"."+ext+"?";
> try {
> //
> file = new File(absolutePath, folderPath);
> if (!file.exists()&&counter==-1) {
> file.mkdirs();
> file2 = new File(file, "/"+fileName+"."+ext);
> androidDialogueTitle = file.getAbsolutePath();
> PApplet.println("checking file1", file2);
> if (file2.exists()) {
> counter ++;
> 
> PApplet.println("File Exists");
> //dbox.main.title.label = s1;
> }
> } else if (counter==-1) {
> fileExists = true;
> counter = 0;
> k = true;
> } else k = true;
> if (overWrite&&writeOnce) {
> k=false;
> } else if (overWrite&&!writeOnce&&writeFile) {
> writeOnce = true;
> k = true;
> }
> boolean k1 = false;
> if (writeFile)
> while (k&&counter<100&&!k1) {
> s1 = fileName+counter+"."+ext+"?";
> try { 
> 
> file2 = new File(absolutePath+"/"+folderPath+"/"+fileName+counter+"."+ext);
> file3 = new File(absolutePath+"/"+folderPath+"/"+fileName+(counter)+"."+ext);
> androidDialogueTitle = file3.getAbsolutePath();
> if (file2.exists()) { 
> counter++;
> } else {
> PApplet.println("checking file2", file2);
> //output = new FileWriter(file2, append);
> k = false;
> k1 = true;
> break;
> }
> } 
> catch (Exception e) { 
> PApplet.println("Error while saving file: " + e);
> }
> }
> if (k1||!writeFile) {
> //PApplet.println("file",file);
> //PApplet.println("Fname",folderName);
> //PApplet.println("fileName",fileName);
> //PApplet.println("counter",counter);
> //PApplet.println("ext",ext);
> if (file2==null&&counter<0)file2 = new File(file+"/"+fileName+"."+ext); 
> else if (file2==null)file2 = new File(file+"/"+fileName+"."+ext); 
> if (output==null) {
> //img.save(file+"/"+fileName+counter+"."+ext);
> 
> if (writeFile)output = new FileWriter(file2, append);
> PApplet.println("File saved successfully.");
> //use write or append
> }
> }
> if (reWrite) {
> file2 = new File(file+"/"+fileName+counter+"."+ext); 
> output = new FileWriter(file2, append);
> }
> println("write file", folderPath, fileName, counter, ext);
> if (reWrite)overWrite = true;
> } 
> catch (IOException e) {
> e.printStackTrace();
> }
> };
> 
> void listen() {
> //if(writeFile&&dbox.main.getButton(0).click)checkLocation();
> };
> 
> void setLocation(String s) {
> if (getPermission)getAndroidInfo();
> location = s;
> folderPath = s.substring(0, s.lastIndexOf("/"));
> fileName = s.replace(folderPath+"/", "");
> getExt(fileName);
> PApplet.println("Fname", folderPath);
> PApplet.println("fileName", fileName);
> PApplet.println("counter", counter);
> PApplet.println("ext", ext);
> checkLocation();
> init();
> }
> 
> void getExt(String location) {
> 
> int count = 0;
> fileName = location.substring(0, location.indexOf("."));
> ext = location.replace(fileName, "");
> ext = ext.replace(".", "");
> ext = ext.replace(fileName, "");
> };
> 
> void dialogBox() {
> 
> msg = new TextView(activity); 
> msg.setBackgroundColor(Color.BLUE);
> msg.setTextSize(32);
> msg.setText(dialogueBody); 
> msg.setGravity(Gravity.CENTER_HORIZONTAL); 
> msg.setTextColor(Color.WHITE); 
> 
> activity.runOnUiThread(new Runnable() {
> public void run() {
> AlertDialog.Builder builder = new AlertDialog.Builder(activity);
> builder.setView(msg);
>         
> androidDialogueTitle += " "+fileName+"."+ext+"?";
> builder.setTitle(androidDialogueTitle);
> builder.setPositiveButton(dialogueB1Title, 
> new DialogInterface.OnClickListener() {
> public void onClick(DialogInterface dialog, 
> int which) {
> writeFile = true;
> overWrite = false;
> reWrite = true;
>               
> }
> }
> );
> builder.setNegativeButton(dialogueB2Title, 
> new DialogInterface.OnClickListener() {
> public void onClick(DialogInterface dialog, 
> int which) {
> writeFile = true;
> overWrite = true;
> //act.finish();
> }
> }
> )
> .show();
> }
> }
> );
> };
>   
> void setAndroidDialogue(String s1,String s2){
> dialogueB1Title = s1;
> dialogueB2Title = s2;
>     
> };
>   
> void setAndroidDialogue(String s1,String s2,String s3){
> androidDialogueTitle = s1;
> dialogueB1Title = s2;
> dialogueB2Title = s3;
>     
> };
>   
> void setAndroidDialogueTitle(String s1){
> androidDialogueTitle = s1;
> };
>   
> void setDialogueColor(){
>     
> };
> 
> public boolean click() {
> boolean k = false;
> if (pos()&&applet.mousePressed&&!click) {
> click = true;
> k = false;
> } else if (click&&!applet.mousePressed) {
> k = true;
> click = false;
> }
> return k;
> };
> 
> public boolean pos(PVector mouse) {
> return mouse.x>x&&mouse.x<x+w&&mouse.y>y&&mouse.y<y+h;
> };
> 
> public boolean pos() {
> return applet.mouseX>x&&applet.mouseX<x+w&&applet.mouseY>y&&applet.mouseY<y+h;
> };
> };
> 
> ```

sketch file

> **Summary**
>
> ```auto
> import java.io.BufferedReader;
> import java.io.BufferedWriter;
> import java.io.File;
> import java.io.FileInputStream;
> import java.io.FileNotFoundException;
> import java.io.FileOutputStream;
> import java.io.FileReader;
> import java.io.FileWriter;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.io.OutputStreamWriter;
> import java.io.PrintWriter;
> 
> import android.app.Activity;
> import android.content.Context;
> import android.os.Environment;
> import android.content.DialogInterface;
> import android.graphics.Color;
> import android.widget.TextView;
> import android.view.Gravity;
> import processing.core.PApplet;
> import android.app.Activity;
> import android.app.AlertDialog;
> 
> fileOutput f;
> 
> String s2 = "oifoifnowibf";
> void settings() {
> size(600, 600, P2D);
> };
> 
> public void setup() {
> 
> f = new fileOutput(this);
> f.setLocation("notes/test.txt");
> f.setAndroidDialogue("No","Yessss");
> };
> 
> public void draw() {
> background(255);
> if (f.fileContent!=null) {
> fill(0);
> text(f.counter, 20, 10);
> text(f.fileContent, 20, 20);
> } else {
> fill(0);
> text("no file", 20, 20);
> }
> };
> 
> void mousePressed() {
> if (f.writeFile) {
> f.writeLn(s2+hour()+":"+minute()+":"+second());
> f.close();
> f.loadStrings();
> }
> if(!f.writeFile)f.dialogBox();
> };
> 
> ```

Permission

> **Summary**
>
> ```auto
> public class Permission{
>   
> PApplet parent;
> String p;
> 
> public Permission(PApplet pParent,String permissionName) {
> p = permissionName;
> parent = pParent;
> parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
> println(permissionName);
> };
> 
> public void onPermissionResult(boolean granted) {
> if (!granted) {
> PApplet.println("User did not grant",p," permission.",p,"is disabled.");
> }
> };
> 
> };
> 
> ```

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [May 14, 2021, 3:07am UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/5 "2021-05-14T03:07:06Z")

</div>

Here is an all in one solution to save and read files on android. It might be restricted in some locations but for it writes to external storage no problem and will request permissions for you. Also I have packaged the permission class inside of the jar so if you want to you can simply call a new permission as follows.

To clarify you have the library that you can add to any sketch, make sure you are making use of the ketai library which is also attached.

The `kboard` folder contains and example sketch to show how to access the relevant functions.

The `Bms.output.textBox` can be repositioned with `Bms.output.textBox.setPos(float x,float y)`;

> **[paulgoux/fileWriter-Android](https://github.com/paulgoux/fileWriter-Android)**
>
> file writer reader for android. Contribute to paulgoux/fileWriter-Android development by creating an account on GitHub.

```auto
Permission p;

void setup(){
p = new Permission("CAMERA");
}

```

make sure your permission is also requested in your ide, whichever version that is. No need to make any changes to the xml file, good to go from the start.

please note there are still a few more tweaks required

---

<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:** [February 1, 2022, 10:26pm UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/6 "2022-02-01T22:26:16Z")

</div>

I sure hope this works because I’m flat out of ideas on how to write to the external storage.

---

<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:** [February 2, 2022, 7:29pm UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/7 "2022-02-02T19:29:01Z")

</div>

Hi guys, for anyone suffering the “permission not granted” error, uninstall the application and re install it. Took me 2 hours to figure this out. BUT IT WORKS!!

---

<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:** [February 5, 2022, 4:39am UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/8 "2022-02-05T04:39:22Z")

</div>

Although I REALLY appreciate this, and would have NEVER figured it out without you, there’s 2 small problems. One is a glitch. In your void saveMyImage(). My file will NOT save if the folder ALREADY EXISTS. If the folder DOES NOT exist then the program will make the folder and save the file normally. I highlighted the problems in the code here:

```auto
void saveMyImage(String sf, String tf){
  try{
    String absolute_path = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
    
    // Here's the first problem. This isn't a file. It's a folder. 
    // so it should be named either
    // File folder = new File(absolute_path+"/"+sf);
    // or
    // File directory = new File(absolute_path+"/"+sf);
    File file = new File(absolute_path+"/"+sf);
    println(file);
    
    //Here's the big problem. Since it's
    //a folder, this checks if the FOLDER
    //exists, not the file. So if the 
    //folder MyImageFolder exists then the
    //file will NOT be saved. It will only
    //save the file if the folder does NOT
    //exist. 
    if (!file.exists()){
      boolean success = true;
      success = file.mkdirs();
      if(success){
        save(file+"/"+tf);
        image_saved = true;
        println("File saved successfully.");
        println("Path",absolute_path,"File",file);
      }else{
        println("no File");
        println("Path",absolute_path,"File",file);
      }
    }
    
    //after this, there's nothing called
    //if(file.exists()) to write the file
    //if the folder exists. 
    
    
  }catch (Exception e){
    println("Error while saving file: " + e);
  }
};

```

That and I fixed the problems here:

```auto
void saveMyImage(String sf, String tf){
  try{
    String absolute_path = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
    File directory = new File(absolute_path+"/"+sf);
    println(directory +" printlning file");
    
    if(!directory.exists()){
      println("directory.exists() = false");
      boolean MadeDirectory = true;
      MadeDirectory = directory.mkdirs();
      if(MadeDirectory){
        println("successfully made folder or directory to save file in");
        save(directory+"/"+tf);
        File file = new File(absolute_path+"/"+sf+"/"+tf);
        if(file.exists()){
          image_saved = true;
          println("File saved successfully.");
          println("Path",absolute_path,"directory",directory);
        }
        if(!file.exists()){
          image_saved = false;
          println("error: although folder was created, file could not be saved.");
          println("Path",absolute_path,"directory",directory);
        }
      }
      if(!MadeDirectory){
        println("error: could not create folder or directory");
        println("Path",absolute_path,"directory",directory);
      }
    }
    
    if(directory.exists()){
      println("directory.exists() = true");
      
      println("folder to save file in already exists. Attempting to save file...");
        save(directory+"/"+tf);
        File file = new File(absolute_path+"/"+sf+"/"+tf);
        if(file.exists()){
          image_saved = true;
          println("File saved successfully.");
          println("Path",absolute_path,"directory",directory);
        }
        if(!file.exists()){
          image_saved = false;
          println("error: although folder exists, file could not be saved.");
          println("Path",absolute_path,"directory",directory);
        }
      
      
    }
    
  }catch(Exception e){
    println("Error while saving file: " + e);
    println("could not make file or folder.");
    println("perhaps the permission was");
    println("not granted? Maybe try");
    println("uninstalling and re-installing.");
  }
}; 

```

But I REALLY thank you for showing me what you did! This was really good! I learned a lot!!!

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [February 5, 2022, 4:53am UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/9 "2022-02-05T04:53:24Z")

</div>

Thanks for the the update, and no worries, I know I struggled on this a while back because resources were scarce and I didnt understand android studio.

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [February 5, 2022, 4:57am UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/10 "2022-02-05T04:57:46Z")

</div>

I still have a library in the works to handle files load and save requests and load folder, it can use a built in folder file picker or custom folder picker. Maybe with a bit of motivation I might hopefully finish it some time. 🙂

---

<div class="post-metadata">

**Author:** ![erkosone](https://avatars.discourse-cdn.com/v4/letter/e/ba9def/32.png) [@erkosone](https://discourse.processing.org/u/erkosone)\
**Post date:** [January 5, 2026, 5:25am UTC](https://discourse.processing.org/t/read-and-write-images-and-text-files-android/29947/11 "2026-01-05T05:25:11Z")

</div>

si utilizas deepseek la terminaras en 1 minuto, no tiene sentido matarte con tanto trabajo, simplemente copia y pega el codigo y pidele lo que necesitas, el hara el trabajo y te explicará como y por que, y tu aprenderas. no programes como hace 60 años. un saludo 😉
