How can I navigate and edit a txt file in Java [duplicate]

2

I have a txt file with a text in it I searched the internet I found some methods for writing and reading, however I have to edit a file that is standard so changing only some parts of the file. What can I use to do this function? For example, in the first line of the file the character 8 to 15 will be replaced by some value that I will type, or a value of a variable.

    
asked by anonymous 12.05.2016 / 17:29

1 answer

2

The code below loads all lines of the text file into memory, changes the characters 8 to 15 of the first line, and saves all the lines, including the changed line, back to file:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("c:/temp/arquivo.txt");
        List<String> linhas = Files.readAllLines(path);

        String novoConteudo = 
            linhas.get(0).substring(0, 7) + "conteudo" + linhas.get(0).substring(15);

        linhas.remove(0);
        linhas.add(0, novoConteudo);

        Files.write(path, linhas);
    }
}

* You may have to consider more aspects like performance, encoding and warranties of the current content of the first line (to avoid exceptions from index out of range ). p>     

12.05.2016 / 18:18