-
-
Save Make-a-tronik/6093586 to your computer and use it in GitHub Desktop.
Ejemplo actualizado haciendo uso de la clase Log, para la lectura y escritura de archivos TXT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Log log; //Nuevo objeto de la clase Log | |
int id=0; | |
int R, G, B; | |
String fileName="archivo.txt"; | |
void setup() { | |
size(400, 600); | |
//Crea ventana para seleccionar archivo | |
selectInput("Selecciona un archivo:", "fileSelected"); | |
} | |
void draw() { | |
} | |
//Callback para seleccionar archivo | |
void fileSelected(File selection) { | |
if (selection == null) { //Si la seleccion fue nula | |
println("La ventana se ha cerrado o el usuario selecciono cancelar."); | |
} | |
else { | |
fileName=selection.getName(); //Obtenemos el nombre del archivo | |
String lines[] = loadStrings(fileName); //Leemos los datos de ese archivo antes de sobreescribir | |
log= new Log(fileName, true); //Creamos el nuevo archivo, activamos la opcion de sobreescribir | |
//Restauramos los datos leidos | |
println(lines.length + " lineas de datos leidos"); | |
for (int i = 0 ; i < lines.length; i++) { | |
log.write(lines[i]); //Rescribimos los datos que ya esxistian | |
String[] data=splitTokens(lines[i], ",;"); //Separamos los parametros | |
//Redibujamos los puntos almacenados con los datos guardados | |
drawEllipse(int(data[0]), int(data[1]), int(data[2]), int(data[3]), int(data[4]), int(data[5])); | |
} | |
id=lines.length; | |
} | |
} | |
//Funcion para dibujar elipses a partir de los parametros almacenados | |
void drawEllipse(int id, int x, int y, int R, int G, int B) { | |
fill(color(R, G, B)); | |
ellipse(x, y, 10, 10); | |
text(id, x+7, y+5); | |
} | |
//Cuando se presiona el mouse | |
void mousePressed() { | |
//Generamos los colores para un nuevo dato | |
R=(int) random(0, 255); | |
G=(int) random(0, 255); | |
B=(int) random(0, 255); | |
drawEllipse(id, mouseX, mouseY, R, G, B); //Dibujamos punto | |
log.write(id+","+mouseX+","+mouseY+","+R+","+G+","+B); //Escribimos las coordenadas del punto | |
id++; | |
} | |
//Cuando se presiona la tecla "c" | |
void keyPressed() { | |
switch(key) { | |
case 'c': | |
log.close(); //Se cierra el archivo | |
println("Archivo cerrado"); | |
exit(); //Cerramos el programa | |
break; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Inicia clase Log | |
class Log { | |
private PrintWriter output; //Permite la creacion de archivos | |
private String path= sketchPath; //Variable para guardar ruta de archivo | |
private String fileName; //Variable para el nombre del archivo | |
private int id=1; //id del archivo, se usa para renombrar | |
//Constructor de la clase | |
Log(String fileName, boolean overwrite) { | |
this.fileName=fileName; //Asigamos nombre del archivo | |
if (exist(this.fileName) && overwrite==false) { //comprobamos si ya existe el nombre del archivo con la funcion exist() | |
rename(); //Si es verdadero se llama a la funcion rename() | |
output= createWriter(this.fileName); //Se crea el archivo con el nombre nuevo | |
} | |
else { | |
output= createWriter(this.fileName); //Si no existe, se crea sin renombrar | |
} | |
} | |
//Crea una lista de los archivos existentes en el directorio actual | |
private String[] listFileNames(String dir) { //recibe como parametro la ruta actual | |
File file = new File(dir); //Crea un objeto de la clase File | |
if (file.isDirectory()) { //Comprobamos que sea un directorio y no un archivo | |
String names[] = file.list(); //Cargamos la lista de archivos en el vector names[] | |
return names; //regresamos names[] | |
} | |
else { | |
return null; //En caso de que sea un archivo se regresa null | |
} | |
} | |
//Comprueba si el archivo ya existe | |
private boolean exist(String fileName) { //recibe como parametro el nombre del archivo | |
String[] filenames = listFileNames(path); //llama a la funcion listFileNames para obtener la lista de archivos | |
for (int x=0; x<=filenames.length-1;x++) { //Se comprueba por medio de un for la existencia del archivo, recorre todo el vector | |
if (fileName.equals(filenames[x])) { //Si el nombre de un archivo existente coincide con el que se propuso | |
return true; //Regresa verdadero | |
} | |
} | |
return false; //Regresa falso | |
} | |
//Renombra el archivo para no sobreescribir | |
private void rename() { | |
String newName=(split(fileName, ".")[0]+"_"+str(id)+"."+split(fileName, ".")[1]); //Al nombre original se le asigna un indicador haciendo uso del id | |
if (exist(newName)) { //Se comprueba si archivo con el nuevo nombre existe | |
id++; //Se incrementa id hasta que se encuentra un archivo inexistente | |
rename(); //Es recursiva en caso de que siga exisitiendo el nombre | |
} | |
else { | |
fileName=newName; //Se regresa el nuevo nombre | |
return; | |
} | |
} | |
//Cierra el archivo, para que sea utilizable | |
public void close() { | |
output.flush(); //Vaciamos buffer de escritura | |
output.close(); //Cerramos el archivo | |
} | |
//Escribe datos nuevos | |
public void write(String data) { | |
output.println(data+";"); //Concatena los datos nuevos y asigna fin de linea | |
} | |
//Regresa el nombre final del archivo | |
public String getName(){ | |
return fileName; | |
} | |
}//Termina clase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment