Filewriter for Android

Not sure if there is already a simple solution to writing text files on android, so here goes.

import java.io.BufferedWriter;
import java.io.FileWriter;
import android.os.Environment;
import android.os.Build ;
import android.app.Activity;
import android.content.Context;
 
Activity activity ;
Context context ;

int maxFolderSize = 1000;
fileOutput output;
boolean mdown = false;
String loc = "positions.txt";

File SDcard ; //emulated .... e.g. /storage/emulated/0

Permission storage;

void setup() {
  
  output = new fileOutput(this,loc,true);
  //output.checkLocation(loc);
  //output.open();
  storage = new Permission(this,"WRITE_EXTERNAL_STORAGE");
  // Create a new file in the sketch directory
  
}

void draw() {
  point(mouseX, mouseY);
  //add condition here before calling
  //click anywhere on the canvas to save
  if(mousePressed&&!mdown){
    output.write_("hello");
    mdown = true;
  }
  
  if(!mousePressed)mdown = false;
  
  //use output.saveData("parameter i " + "parameter i++".....)
}

class fileOutput {
  PrintWriter output;
  boolean save, onMouseUp, mdown, debug, append, appendFile, match,append2,overWrite;
  int counter, counter2;
  File file;
  File[] SDcards ; 
  String location, filePath,folderPath = "";
  PApplet applet;
  
  
  fileOutput() {
    appendFile = true;
  };

  fileOutput(boolean a) {
    overWrite = true;
    appendFile = true;
  };

  fileOutput(PApplet applet,String location) {
    //appendFile = true;
    this.applet = applet;
    Activity activity = applet.getActivity();
    Context context = activity.getApplicationContext();
    SDcards = context.getExternalFilesDirs(null);
    checkLocation(location);
    open();
  };
  
  //currently unused
  fileOutput(String location, boolean m) {
    if(m)appendFile = true;
    checkLocation(location);
    //open();
    //file = dataFile(location);
    //filePath = file.getPath();
  };
  
  fileOutput(PApplet applet,String location, boolean m) {
    if(m)appendFile = true;
    
    this.applet = applet;
    Activity activity = applet.getActivity();
    Context context = activity.getApplicationContext();
    SDcards = context.getExternalFilesDirs(null);
    //println(SDcards.length);
    
    checkLocation(location);
    open();
    //file = dataFile(location);
    //filePath = file.getPath();
  };

  void checkLocation(String location){
    
    int count = 0;
    folderPath = SDcards[0].toString()+"//" +folderPath;
    for(int i=location.length()-1;i>-1;i--){
      char c = location.charAt(i);

      if(c=='\\'){
        folderPath = location.substring(0,i);
        this.location = location.substring(i,location.length());
        count ++;
        break;
      }
    }
    if(count==0)this.location = location;
    
    folderPath = SDcards[0].toString()+"/" +folderPath;
    this.location = this.location.replace("\\","");
    String s1 = folderPath;
    String s2 = this.location.replace("\\","");
    println("folder",folderPath,"file",location);


    println("checkLocation:",s1 + "/" + counter + "/" + s2);
  };

  void update(String folder, String file,int counter ){
    //filePath = folder + "\\" + file;
    this.folderPath = folder ;
    this.location = file;
    this.counter = counter;
    appendFile = false;
    overWrite = true;
  };

  void saveData() {
    if (mdown()) {
      checkFile( location, append);
    }
    if (mdown)
      output.println(mouseX + ",+ " + mouseY);
    close();
  };

  void open() {
    checkFile(location, append);
  };

  void write(String s) {
    //function to write without overwriting or append
    if(output!=null)
    {
      output.println(s);
      output.flush();
    }
    else print("Create Save File");
  };

  void write(float f) {
    output.println(str(f));
  };

  void write_(String s) {
    //function to overwrite file
    output.print(s);
    if(output!=null){
      println("success",s);
      output.flush(); // Writes the remaining data to the file
      output.close(); // Finishes the file
    }else println("failed",location,folderPath);
  };

  void write(String []s) {
    String s1 = "";
    for (int i=0; i<s.length; i++) {
      s1 += s[i];
    }
    if(s1!=null&&output!=null)output.println(s1);
  };

  void close() {
    if(output!=null){
      output.flush(); // Writes the remaining data to the file
      output.close(); // Finishes the file
    }else println(location,folderPath);
  };

  boolean onMouseUp() {
    boolean k = false;
    if (pos()&&!mousePressed&&onMouseUp) {
      onMouseUp = false;
    } else if (pos()&&mousePressed&&!onMouseUp) {
      output.println(counter);
      onMouseUp = true;
      k = false;
    } else if (onMouseUp&&!mousePressed) {
      k = true;
      onMouseUp = false;
      counter ++;
    }

    return k;
  };

  boolean mdown() {
    boolean k= false;
    if (mdown)k = false;
    if (mousePressed&&!mdown) {
      mdown = true;
      k = true;
    }
    if (!mousePressed)mdown = false;    
    return k;
  };

  boolean pos() {
    return mouseX>0&&mouseX<width&&mouseY>0&&mouseY<height;
  };

  void checkFile(String location, boolean append) {
    if (appendFile) {

      file = dataFile(folderPath + "/" + location);
      filePath = file.getPath();
      filePath = filePath.replace(location, "");
      String[] list = null;
      if(debug)println("checkFile");
      //println(filePath);
      if (listNames(filePath)!=null&&!match) {
        
        list = listNames(filePath);
        boolean b = false;
        for(int j=maxFolderSize;j>-1;j--){
          //println(j);
          if(b)break;
          counter = j;
          for (int i=list.length-1;i>-1; i--) {

            int n = int(list[i]);
            if (j == n){
              //println(j + ", " + list[i]);
              counter = j;
              b = true;
              break;
            }}}
          match = true;
          if(!b)counter = -1;
          if(counter>=0)counter = counter + 1;
          else counter = 0;
          
          //println(counter);
      }
      else{
       file = dataFile(folderPath + "/" + location);
       filePath = file.getPath();
       filePath = filePath.replace(location, ""); 
      }
      file = dataFile(folderPath + "/" + counter + location);
      filePath = file.getPath();
      appendFile = false;
      append = true;
    }
    if(file!=null&&(!file.exists()&&!append2)) {
      //output = createWriter("/data/" + folderPath + "/" + counter + location);
      //println("folderpath " + folderPath + "\\" + counter+"\\" + location);
    }

    if(overWrite||output == null){
      output = createWriter(folderPath + "/" + counter + "/"+ location);
      //println("new folderpath " + folderPath + counter + "\\" + location);
      file = dataFile(folderPath + "/" + counter + "/" + location);
      filePath = file.getPath();
      filePath = filePath.replace(location, ""); 
    }
    if (debug) println(filePath);
    try {

      FileWriter fw = new FileWriter(file, append);///true = append
      BufferedWriter bw = new BufferedWriter(fw);
      output = new PrintWriter(bw);
      println("success",output);
    }
    catch(IOException ioe) {
      System.out.println("Exception ");
      ioe.printStackTrace();
      println(filePath);
    }
  };
};

String[] listNames(String dir) {
  
  if(dir==null)return null;
  File file  = new File(dir);
  if (file.isDirectory()) {
    String names[] = file.list();
    return names;
  } else {
    // If it's not a directory
    return null;
  }
};

int totalFiles(String dir) {
  File file  = new File(dir);
  if (file.isDirectory()) {
    String names[] = file.list();
    return names.length;
  } else {
    // If it's not a directory
    return -1;
  }
};

String getFileExtension(File file) {
  String fileName = file.getName();
  if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
  return fileName.substring(fileName.lastIndexOf(".")+1);
  else return null;
};
public class Permission{
  
  PApplet parent;
  
  public boolean requestedPortraitImage = false;

  public Permission(PApplet pParent,String 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. Camera is disabled.");
    }
  };

};

I have to tried to keep it as simple as possible. The two main constructors we care about are these one

fileOutput(PApplet applet,String location) {
    //appendFile = true;
    this.applet = applet;
    Activity activity = applet.getActivity();
    Context context = activity.getApplicationContext();
    SDcards = context.getExternalFilesDirs(null);
    checkLocation(location);
    open();
  };
  
  //currently unused
  fileOutput(String location, boolean m) {
    if(m)appendFile = true;
    checkLocation(location);
    //open();
    //file = dataFile(location);
    //filePath = file.getPath();
  };
  
  fileOutput(PApplet applet,String location, boolean m) {
    if(m)appendFile = true;
    
    this.applet = applet;
    Activity activity = applet.getActivity();
    Context context = activity.getApplicationContext();
    SDcards = context.getExternalFilesDirs(null);
    //println(SDcards.length);
    
    checkLocation(location);
    open();
    //file = dataFile(location);
    //filePath = file.getPath();
  };

The first one creates and or overwrites an existing file whilst the second one allows you to append to a new destination. Each write places the folder in the data folder of the app, this can be changed as the code doesnt specifically make use of the data folder but instead uses the buffered writer which you can point to any folder it just happens to be pointed to the data folder, I’ll update later.

The second constructor allows you to append the file to a new folder. Initially everything goes in to folder 0, if append is set to true and there are already folders, the sketch will check the latest number or highest index, and create a folder with an index 1 greater than the last folder and will place your file/ folder in there.

Here is a version for pc builds

class fileOutput {
  PrintWriter output;
  boolean save, onMouseUp, mdown, debug, append, appendFile, match,append2,overWrite;
  int counter, counter2;
  File file;
  String location, filePath,folderPath = "";

  fileOutput() {
    appendFile = true;
  };

  fileOutput(boolean a) {
    overWrite = true;
    appendFile = true;
  };

  fileOutput(String location) {
    //appendFile = true;
    checkLocation(location);
    open();
  };
  
  fileOutput(String location, boolean m) {
    appendFile = true;
    checkLocation(location);
    open();
    file = dataFile(location);
    filePath = file.getPath();
  };

  void checkLocation(String location){
    int count = 0;
    for(int i=location.length()-1;i>-1;i--){
      char c = location.charAt(i);

      if(c=='\\'){
        folderPath = location.substring(0,i);
        this.location = location.substring(i,location.length());
        count ++;
        break;
      }
    }
    if(count==0)this.location = location;

    String s1 = folderPath.replace("\\","");
    String s2 = this.location.replace("\\","");



    println("checkLocation: " + s1 + "\\" + counter + "\\" + s2);
  };

  void update(String folder, String file,int counter ){
    //filePath = folder + "\\" + file;
    this.folderPath = folder +"\\";
    this.location = file;
    this.counter = counter;
    appendFile = false;
    overWrite = true;
  };

  void saveData() {
    if (mdown()) {
      checkFile( location, append);
    }
    if (mdown)
      output.println(mouseX + ",+ " + mouseY);
    close();
  };

  void open() {
    checkFile(location, append);
  };

  void write(String s) {
    // use this one to append the file created
    if(output!=null){
      output.println(s);
      println("successful write",s);
      output.flush(); // Writes the remaining data to the file
      //output.close(); // Finishes the file
    }
    else print("Create Save File");
  };

  void write(float f) {
    output.println(str(f));
  };

  void write_(String s) {
    //use this one to overwrite file
    //output.write(s);
    output.println(s);
    if(output!=null){
      println("successful overwrite",s);
      output.flush(); // Writes the remaining data to the file
      output.close(); // Finishes the file
    }else println("failed",location,folderPath);
  };

  void write(String []s) {
    String s1 = "";
    for (int i=0; i<s.length; i++) {
      s1 += s[i];
    }
    if(s1!=null&&output!=null)output.println(s1);
  };

  void close() {
    if(output!=null){
      output.flush(); // Writes the remaining data to the file
      output.close(); // Finishes the file
    }else println(location,folderPath);
  };

  boolean onMouseUp() {
    boolean k = false;
    if (pos()&&!mousePressed&&onMouseUp) {
      onMouseUp = false;
    } else if (pos()&&mousePressed&&!onMouseUp) {
      output.println(counter);
      onMouseUp = true;
      k = false;
    } else if (onMouseUp&&!mousePressed) {
      k = true;
      onMouseUp = false;
      counter ++;
    }

    return k;
  };

  boolean mdown() {
    boolean k= false;
    if (mdown)k = false;
    if (mousePressed&&!mdown) {
      mdown = true;
      k = true;
    }
    if (!mousePressed)mdown = false;    
    return k;
  };

  boolean pos() {
    return mouseX>0&&mouseX<width&&mouseY>0&&mouseY<height;
  };

  void checkFile(String location, boolean append) {
    if (appendFile) {

      file = dataFile(folderPath + "/" + location);
      filePath = file.getPath();
      filePath = filePath.replace(location, "");
      String[] list = null;
      if(debug)println("checkFile");
      if (listNames(filePath)!=null&&!match) {
        println(filePath);
        
        list = listNames(filePath);
        boolean b = false;
        for(int j=maxFolderSize;j>-1;j--){
          //println(j);
          if(b)break;
          counter = j;
          for (int i=list.length-1;i>-1; i--) {

            int n = int(list[i]);
            if (j == n){
              //println(j + ", " + list[i]);
              counter = j;
              b = true;
              break;
            }}}
          match = true;
          if(!b)counter = -1;
          if(counter>=0)counter = counter + 1;
          else counter = 0;
          
          //println(counter);
      }
      else{
       file = dataFile(folderPath + "/" + location);
       filePath = file.getPath();
       filePath = filePath.replace(location, ""); 
      }
      file = dataFile(folderPath + "/" + counter + location);
      filePath = file.getPath();
      //appendFile = false;
      //append = true;
    }
    if(file!=null&&(!file.exists()&&!append2)) {
      //output = createWriter("/data/" + folderPath + "/" + counter + location);
      //println("folderpath " + folderPath + "\\" + counter+"\\" + location);
    }
    //overWrite||
    if(output == null){
      output = createWriter("/data/" + folderPath + "/" + counter + "/"+ location);
      //println("new folderpath " + folderPath + counter + "\\" + location);
      file = dataFile(folderPath + "/" + counter + "/" + location);
      filePath = file.getPath();
      filePath = filePath.replace(location, ""); 
    }
    if (debug) println(filePath);
    try {

      FileWriter fw = new FileWriter(file, true);///true = append
      BufferedWriter bw = new BufferedWriter(fw);
      output = new PrintWriter(bw);
    }
    catch(IOException ioe) {
      System.out.println("Exception ");
      ioe.printStackTrace();
      println(filePath);
    }
  };
};

String[] listNames(String dir) {
  
  if(dir==null)return null;
  File file  = new File(dir);
  if (file.isDirectory()) {
    String names[] = file.list();
    return names;
  } else {
    // If it's not a directory
    return null;
  }
};

int totalFiles(String dir) {
  File file  = new File(dir);
  if (file.isDirectory()) {
    String names[] = file.list();
    return names.length;
  } else {
    // If it's not a directory
    return -1;
  }
};

String getFileExtension(File file) {
  String fileName = file.getName();
  if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
  return fileName.substring(fileName.lastIndexOf(".")+1);
  else return null;
};

As for the writing itself, use the write(String s) to append a file, and write_(String)to overwrite the file. Again folder structure will remain this just handles the data inside the file.

Please note there is other functionality, like the option to change the location after creation, but as I started this project a few months ago and never made any comments I can’t exactly remember how it works. I’ll look over it later properly and will comment the code as appropriate.

Just tidying up the code.

Also the name and location of the file to write is set as a single string. Subfolders can be added with th use of \, such as

String loc = "data\\positions.txt";

This will create a new folder for positions.txt in a data folder, in a files folder. Files folder is created for the android version, the pc version just creates a data folder.

1 Like