Writing in the beginning of a text file Java

Solution 1:

You can't really modify it that way - file systems don't generally let you insert data in arbitrary locations - but you can:

  • Create a new file
  • Write the prefix to it
  • Copy the data from the old file to the new file
  • Move the old file to a backup location
  • Move the new file to the old file's location
  • Optionally delete the old backup file

Solution 2:

Just in case it will be useful for someone here is full source code of method to prepend lines to a file using Apache Commons IO library. The code does not read whole file into memory, so will work on files of any size.

public static void prependPrefix(File input, String prefix) throws IOException {
    LineIterator li = FileUtils.lineIterator(input);
    File tempFile = File.createTempFile("prependPrefix", ".tmp");
    BufferedWriter w = new BufferedWriter(new FileWriter(tempFile));
    try {
        w.write(prefix);
        while (li.hasNext()) {
            w.write(li.next());
            w.write("\n");
        }
    } finally {
        IOUtils.closeQuietly(w);
        LineIterator.closeQuietly(li);
    }
    FileUtils.deleteQuietly(input);
    FileUtils.moveFile(tempFile, input);
}

Solution 3:

I think what you want is random access. Check out the related java tutorial. However, I don't believe you can just insert data at an arbitrary point in the file; If I recall correctly, you'd only overwrite the data. If you wanted to insert, you'd have to have your code

  1. copy a block,
  2. overwrite with your new stuff,
  3. copy the next block,
  4. overwrite with the previously copied block,
  5. return to 3 until no more blocks