Saltar al contenido

Java Reemplazar línea en archivo de texto

Sé libre de compartir nuestra página y códigos en tus redes, ayúdanos a hacer crecer nuestra comunidad.

Solución:

En la parte inferior, tengo una solución general para reemplazar líneas en un archivo. Pero primero, aquí está la respuesta a la pregunta específica en cuestión. Función auxiliar:

public static void replaceSelected(String replaceWith, String type) 
    try 
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) 
            inputBuffer.append(line);
            inputBuffer.append('n');
        
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) 
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
         else if (type.equals("1")) 
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        

        // display the new file for debugging
        System.out.println("----------------------------------n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

     catch (Exception e) 
        System.out.println("Problem reading file.");
    

Entonces llámalo:

public static void main(String[] args) 
    replaceSelected("Do the dishes", "1");   


Contenido del archivo de texto original:

lavar los platos0

Alimentar al perro0
limpie mi habitacion 1

Producción:

lavar los platos0
Alimentar al perro0
limpie mi habitacion 1
———————————-
lavar los platos1
Alimentar al perro0
limpie mi habitacion 1

Nuevo contenido del archivo de texto:

lavar los platos1
Alimentar al perro0
limpie mi habitacion 1


Y como nota, si el archivo de texto fuera:

lavar los platos1
Alimentar al perro0
limpie mi habitacion 1

y usaste el método replaceSelected("Do the dishes", "1");simplemente no cambiaría el archivo.


Dado que esta pregunta es bastante específica, agregaré una solución más general aquí para futuros lectores (según el título).

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() 
    try 
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) 
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('n');
        
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

     catch (Exception e) 
        System.out.println("Problem reading file.");
    

Desde Java 7 esto es muy fácil e intuitivo de hacer.

List fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));

for (int i = 0; i < fileContent.size(); i++) 
    if (fileContent.get(i).equals("old line")) 
        fileContent.set(i, "new line");
        break;
    


Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);

Básicamente lees todo el archivo a un Listedite la lista y finalmente vuelva a escribir la lista en el archivo.

FILE_PATH representa el Path del archivo

Si el reemplazo es de diferente longitud:

  1. Lea el archivo hasta que encuentre el string desea reemplazar.
  2. Leer en la memoria la parte después texto que desea reemplazar, todo.
  3. Trunca el archivo al comienzo de la parte que deseas reemplazar.
  4. Escribir reemplazo.
  5. Escriba el resto del archivo del paso 2.

Si el reemplazo es de la misma longitud:

  1. Lea el archivo hasta que encuentre el string desea reemplazar.
  2. Establezca la posición del archivo al inicio de la parte que desea reemplazar.
  3. Reemplazo de escritura, sobrescribiendo parte del archivo.

Esto es lo mejor que puede obtener, con las limitaciones de su pregunta. Sin embargo, al menos el ejemplo en cuestión está reemplazando string de la misma longitud, por lo que la segunda forma debería funcionar.

También tenga en cuenta: las cadenas Java son texto Unicode, mientras que los archivos de texto son bytes con cierta codificación. Si la codificación es UTF8 y su texto no es Latin1 (o ASCII simple de 7 bits), debe verificar la longitud del byte codificado arrayno la longitud de Java string.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *