Java - Sobrescribir un archivo de texto sin borrar la informacion guardada

 
Vista:
Imágen de perfil de Daniel

Sobrescribir un archivo de texto sin borrar la informacion guardada

Publicado por Daniel (1 intervención) el 03/06/2018 02:24:30
Tengo un programa en donde guardo los estados de un semaforo (si esta en rojo, amarillo o verde), la fecha y hora, pero cuando quiero que escriba en la siguiente linea otra informacion se sobrescribe el archivo, que puedo hacer?

Este es el codigo que estoy usando:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String ruta = "";
Path registro = Paths.get(ruta, "Registro de Fecha y Hora.txt");
try {
    BufferedOutputStream Escritor;
    Escritor = new BufferedOutputStream(Files.newOutputStream(registro, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING));
 
 
    registroDatos = String.format("Semaforo:" + "%s \t" + "Fecha:" + "%s \t" + "Hora:" + "%s  \t" + "Estado del semaforo:" + "%s \t", sem1.getName(), this.jLabel4.getText(), this.jLabel3.getText(), Semaforo.EstadoRojo);
    Escritor.write(registroDatos.getBytes());
    Escritor.flush();
 
} catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Se genero un problema en la simulacion. \n \nCerrando aplicacion.");
    System.exit(0);
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Pedro
Val: 305
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Sobrescribir un archivo de texto sin borrar la informacion guardada

Publicado por Pedro (102 intervenciones) el 03/06/2018 10:31:19
Prueba esto a ver si te sirve:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
//Indicamos la ruta al archivo 
File file = new File ("Path a tu archivo ejemplo C:\\Users\Desktop\\arhivodetexto.txt");
 
/*Con true le indicamos que el flujo de bytes lo añada al final del archivo 
de esta manera lo que haya al principio no será borrado*/
FileOutputStream output = new FileOutputStream(file, true);
 
//Creamos el buffer para el flujo de datos
BufferedOutputStream Escritor = new  BufferedOutputStream(output);
 
registroDatos = String.format("Semaforo:" + "%s \t" + "Fecha:" + "%s \t" + "Hora:" + "%s \t" + "Estado del semaforo:" + "%s \t", sem1.getName(), this.jLabel4.getText(), this.jLabel3.getText(), Semaforo.EstadoRojo);
Escritor.write(registroDatos.getBytes());
Escritor.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Se genero un problema en la simulacion. \n \nCerrando aplicacion.");
System.exit(0);
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar