Search code examples
javafilefilewriter

Java-How to insert a string to certain line, say line6, of a txt file


I want to insert a line into a specific location of a .txt file. Now the only way I know is to read out the whole file out as an array, put the given line in the correct place and then write the whole thing back. Is there an easier way to achieve this using Java? My intention is to reduce the file access as much as possible.


Solution

  • Is there an easier way to achieve this using Java?

    With Java 7, unless your insertion point is towards the end of a huge file, I would simply do:

    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    lines.add(position, extraLine);
    Files.write(path, lines, StandardCharsets.UTF_8);