Tags: Code, file, filename, function, io, pde, Processing / Java, utility
For many applications like saving images, PDFs, logs or temporary files one typically wants to use a set filename structure. One such typical structure is “Sketch-####.png”, where # denotes a single number. It is often convenient to not have to keep track of the numerical component, but just assuming that it will update automatically.
This hack describes a simple function which can be used to return the next valid filename in a sequence, so that you won’t have to worry about erasing files. It is very useful if you have a “snapshot” function for saving images of your work-in-progress.
This hack borrows from the "Reading a Sequence.#####.png" processinghack hack, which again borrows from the Processing source. The following function enables you to save files without having to worry about their exact name. The function checks the sequence and finds the next free “spot” in the sequence to save to.
Note that right now there is no bug checking code to see if the given filename structure will result in valid filenames. The function is currently set up to give an error if it has tried 10 000 filenames without a valid hit, which will save you from endless loops but annoy you if you know what you’re doing.
// getIncrementalFilename.pde
// Marius Watz - http://workshop.evolutionzone.com
boolean doSave=false;
void setup() {
println("Hello world!");
size(200,200);
}
void draw() {
String name;
if(doSave) {
name=getIncrementalFilename("sketch-####.tga");
saveFrame(name);
println("Saved "+name);
doSave=false;
}
fill(random(255));
ellipse(random(width),random(height), 10,10);
}
// click to save
public void mousePressed() {
doSave=true;
}
public String getIncrementalFilename(String what) {
String s="",prefix,suffix,padstr,numstr;
int index=0,first,last,count;
File f;
boolean ok;
first=what.indexOf('#');
last=what.lastIndexOf('#');
count=last-first+1;
if( (first!=-1)&& (last-first>0)) {
prefix=what.substring(0, first);
suffix=what.substring(last+1);
// Comment out if you want to use absolute paths
// or if you're not using this inside PApplet
if(sketchPath!=null) prefix=savePath(prefix);
index=0;
ok=false;
do {
padstr="";
numstr=""+index;
for(int i=0; i< count-numstr.length(); i++) padstr+="0";
s=prefix+padstr+numstr+suffix;
f=new File(s);
ok=!f.exists();
index++;
// Provide a panic button. If index > 10000 chances are it's an
// invalid filename.
if(index>10000) ok=true;
}
while(!ok);
// Panic button - comment out if you know what you're doing
if(index> 10000) {
println("getIncrementalFilename thinks there is a problem - "+
"Is there more than 10000 files already in the sequence "+
" or is the filename invalid?");
println("Returning "+prefix+"ERR"+suffix);
return prefix+"ERR"+suffix;
}
}
return s;
}





