Question

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.

Was it helpful?

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);

OTHER TIPS

Try to read and write at the same time by using BufferedReader.

The Idea is to read line and immediately write it to other file.

BufferedReader rd = null;
    BufferedWriter wt = null;

    try {
        rd = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream("/yourfile.txt"), "UTF-8")
                );

        wt = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(
                                "/newfile" + ".txt"), "UTF-8")
                );

        int count = 0;

        for (String line; (line = reader.readLine()) != null;) {

            count++

            if (count == 6) {
                // add your line 
                // wt.write(newline);
            }

            wt.write(line);
            wt.newLine();
        }
    } finally {
        close(wt);
        close(rd);
    }

RandomAccessFile do not solve this problem. It was discussed in this post. You should rewrite file anyway.
You can only read and write it with some buffer, alter it and immidiate write to new to save your program memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top