jueves
abr032014
Pregunta sobre Java
¿Cuál es la salida por consola, y cuál la escrita en el fichero, de ejecutar el siguiente código fuente?
NOTA: tiene más gracia contestar sin hacer uso de IDE que haciendo uso de IDE
package pruebas;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author Jaime Carmona Loeches
*
*/
public class Escritor implements Runnable {
private String nombreFichero = "";
@Override
public void run() {
System.out.println("Escritor ejecutando");
ejecutaLogica(0);
}
public Escritor(String nombreFichero) {
System.out.println("Escritor inicializado");
this.nombreFichero = nombreFichero;
}
private synchronized void ejecutaLogica(int numEjecucion) {
System.out.println(numEjecucion);
FileWriter fw = null;
BufferedWriter bw = null;
try {
File file = new File(nombreFichero);
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
for (int i = 0; i < 10; i++) {
String texto = numEjecucion + ":" + i;
bw.write(texto + "\n");
}
cierraRecursos(fw, bw);
numEjecucion++;
if (numEjecucion < 2)
ejecutaLogica(numEjecucion);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private void cierraRecursos(FileWriter fw, BufferedWriter bw) {
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) {
String nombreFichero = "out.txt";
Escritor escritor = new Escritor(nombreFichero);
escritor.run();
}
}

jcarmonaloeches
Reader Comments (2)
Escritor inicializado Escritor ejecutando 0 1 out.txt 1 : 0 1 : 1 1 : 2 1 : 3 1 : 4 1 : 5 1 : 6 1 : 7 1 : 8 1 : 9
Hola José, gracias por tu respuesta. ¿Puedes argumentar la respuesta por favor?
Un saludo,