Here is an example which writes Float values to a file in one sketch and reads them in another sketch. The Lock file is used to prevent both sketches reading/writing at the same time.
Activate the writer window and press SPACE several times to generate data, then press 's' to save it.
The reader sketch will automatically load the data and delete the file afterwards.
reader.pde
- import java.io.File;
- ArrayList<Float> data;
- String inputFilename = "out.txt";
- String lockFilename = "LO.CK";
- File lockFile, dataFile;
- String writerDataPath = "C:/Users/Tim/Documents/Processing/_tmp/MultipleSketchesPipe/writer/data/";
- void setup(){
- data = new ArrayList<Float>();
- lockFile = new File(writerDataPath + lockFilename);
- dataFile = new File(writerDataPath + inputFilename);
- }
- void draw(){
- checkForNewData();
- }
- void checkForNewData(){
- if(!dataFile.exists()){
- return;
- }
- if(!lockFile.exists()){
- saveStrings(lockFile.getAbsolutePath(), new String[]{"Locked by reader"});
- if(dataFile.exists()){
- String[] sa = loadStrings(dataFile.getAbsolutePath());
- addFloatsToArrayList(sa, data);
- dataFile.delete();
- lockFile.delete();
- }
- }
- }
- void addFloatsToArrayList(String[] sa, ArrayList<Float> list){
- for(String s: sa){
- list.add(new Float(Float.parseFloat(s)));
- println("Reader ~~ added data: " + list.get(list.size()-1));
- }
- }
writer.pde
- import java.io.File;
- ArrayList<Float> data;
- String outputFilename = "out.txt";
- String lockFilename = "LO.CK";
- File outFile;
- File lockFile;
- void setup(){
- data = new ArrayList<Float>();
- outFile = new File(dataPath(outputFilename));
- lockFile = new File(dataPath(lockFilename));
- }
- void draw(){}
- void keyPressed(){
- if(key == ' '){
- Float f = new Float(random(0, 100));
- data.add(f);
- println("Writer ~~ " + f + " added");
- }
- else if(key == 's'){
- while(lockFile.exists()){
- try{
- Thread.sleep(20);
- }catch(Exception e){e.printStackTrace();}
- }
- saveStrings(lockFile.getAbsolutePath(), new String[]{"Locked by writer"});
- saveStrings(outFile.getAbsolutePath(), getStringArray(data));
- println("Writer ~~ saving strings....");
- lockFile.delete();
- }
- }
- String[] getStringArray(ArrayList<Float> list){
- String[] stringa = new String[list.size()];
- for(int i=0; i<list.size(); i++){
- stringa[i] = String.valueOf(list.get(i));
- }
- return stringa;
- }