How can I browse and edit a txt file in Java

Asked

Viewed 2,729 times

2

I have a txt file with a text in it I searched on the internet I found some methods for writing and reading, but I have to edit a file that is standard thus 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 I will type, or a value of a variable.

1 answer

2


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

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 guarantees of the current content of the first line (to avoid exceptions of index out of range).

  • I tested the code and returned the following error : Exception in thread "main" java.nio.charset.Malformedinputexception: Input length = 1 , you know why it occurs

  • Now it worked here, obgd ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.