2

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.

theflyingwolves
  • 191
  • 1
  • 3
  • 10
  • 1
    No, there's no other way. Although you don't need an array for this. – Kayaman Oct 02 '13 at 08:51
  • 1
    @assylias The OP in this question is specifically concerned about reducing access to the file, whereas the duplicate you link doesn't share that concern and the accepted answer suggested just reading to an array. – Duncan Jones Oct 02 '13 at 08:54

3 Answers3

6

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);
assylias
  • 321,522
  • 82
  • 660
  • 783
  • It is superfluous to read all lines to memory. Better is to read line by line, saving each line to temporary file. After achieving the right location, put additional lines and rewrite the rest of the file. On the end, delete original file and rename the temporary one to the original name. – agad Oct 02 '13 at 10:28
  • @agad how do you propose to "rewrite the rest of the file" without reading the original file first?? – assylias Oct 02 '13 at 11:38
  • @assylias of course you must read it, but you don't need to store all lines in memory – agad Oct 02 '13 at 11:42
  • @agad unless the file is big I don't see it as a problem - memory allocation in Java is very cheap... For a larger file that does not fit in memory, you obviously need a different startegy. – assylias Oct 02 '13 at 11:49
  • If the file contains a few lines only, it is not a problem, but, from the question, I have a feeling, that the file contains a few thousands lines or more. – agad Oct 02 '13 at 11:55
2

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);
    }
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
0

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.

Community
  • 1
  • 1
Pavlo K.
  • 371
  • 1
  • 9