How would you erase a line ex: "position 6" in a .txt file or in a String string?

2

Try several ways but I can not do it. One of them would be this and I get an error:

try {
    java.io.BufferedWriter bufferedWriter = new BufferedWriter(new 
    FileWriter("Archivo.txt"));
    bufferedWriter.append("Esto es la linea 1");
    bufferedWriter.flush();
    bufferedWriter.newLine();
    bufferedWriter.append("Esto es la linea 2");
    bufferedWriter.flush();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

The other way that probe is this:

public static void main(String args[]) {
    String fichero = args[0];
    try {
        FileReader fr = new FileReader(fichero);
        BufferedReader br = new BufferedReader(fr);

        String linea;
        while((linea = br.readLine()) != null)
            System.out.println(linea);

        fr.close();
    } catch(Exception e) {
        System.out.println("Excepcion leyendo fichero "+ fichero + ": " + e);
    }
}

but he reads the entire file.

    
asked by Antonio Olvera 29.08.2018 в 00:37
source

1 answer

1

Using java you can delete a line in this way using BufferedReader to read the file and its lines, when making the comparison the file without the line would be written in the file defined by BufferedWriter , remember that in android you can not define routes of your pc:

 String lineToRemove = "posicion 6";

   File inputFile = new File("C:\Data\archivo.txt");
   File outputFile = new File("C:\Data\archivo_nuevo.txt");

    try {
      BufferedReader reader = new BufferedReader(new FileReader(inputFile));
      BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));

    String currentLine;

    while((currentLine = reader.readLine()) != null) {                        
        if(currentLine.trim().equals(lineToRemove)){ 
            continue;
        }
        writer.write(currentLine + System.getProperty("line.separator"));
    }       

    writer.close();
    reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    
answered by 29.08.2018 / 03:28
source