How to overwrite a line from a TXT file in Java?
For example, if I have a file with the following text:
User_1, password_1, Active
User_2, password_2, Active
User_3, password_3, Active
And I want to change it to look like this:
User_1, password_1, not Active
User_2, password_2, Active
User_3, password_3, Active
I just want to overwrite Line 1 of that file. Have tried with the FileWriter
, however, with that library I can only write one line at the end, so it would remain:
User_1, password_1, Active
User_2, password_2, Active
User_3, password_3, Active
User_1, password_1, not Active
I have also tried creating another file in which I am changing lines from the current file and adding them to the new file, to finally delete the previous file. It works, however I do not think it is the most optimal.
2 answers
You can send as a parameter the line position you want to overwrite to the input method, if also the modified line. try this:.
import java.io.File;
import java.io.FileReader;
import javax.swing.JOptionPane;
public class Archivo {
String ruta;
public Archivo() {
}
public Archivo(String ruta){
this.ruta = ruta;
try {
File archivo = new File(this.ruta);
this.ruta = archivo.getCanonicalPath();
} catch (Exception e) {
}
}
public String leerArchivo(){
String cadena = "";
FileReader entrada = null;
try {
entrada = new FileReader(ruta);
int c;
while((c = entrada.read()) != -1){
cadena += (char)c;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al leer archivo: "+e.getMessage());
}
return cadena;
}
public void ingresar(String nuevaLinea, int posicion){
FileWriter fichero = null;
PrintWriter escritor = null;
try {
fichero = new FileWriter(ruta);
escritor = new PrintWriter(fichero);
escritor.flush();
String split[] = leerArchivo().split("\n");
split[posicion] = nuevaLinea;
for(int x = 0; x < split.length; x++){
escritor.write(split[x]);
escritor.println();
}
escritor.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error al escribir en el archivo de texto: "+e.getMessage());
} finally {
if(fichero != null){
try {
fichero.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error al cerrar archivo de texto: "+e.getMessage());
}
}
}
}
}
With RandomAccessFile you could achieve this, but considering that there are two more characters to write "NO"
so for this example you need the line to have 3 more spaces Usuario_1,contrasena_1,Activo___
(_) spaces to then do something with this
/* RW , para Lectura(Read) y Escritura (Writer) */
RandomAccessFile archivo = new RandomAccessFile("./Archivo.txt", "rw");
/* Posicionar al inicio del archivo, con seek te posicionas en el lugar
que desees del archivo */
archivo.seek(0);
/* Escribir la cadena */
archivo.writeBytes("Usuario_1,contrasena_1,NO Activo");
archivo.close();/* Cerrar el archivo importante */
The other option is to read the entire file and replace the line word and then rewrite everything again (I prefer RandomAccesFile)
BufferedReader file = new BufferedReader(new FileReader("./Archivo.txt"));
String line;String input = "";
while((line = file.readLine()) != null){
/* Podemos verificar si es Usuario_1 y \r\n es para hacer el
Salto de Línea y tener el formato original */
if(line.contains("Usuario_1"))
input += line.replaceAll("Activo", "NO Activo \r\n");
else
input += line+"\r\n";
}
FileOutputStream fileOut = new FileOutputStream("./Archivo.txt");
fileOut.write(input.getBytes());
fileOut.close();