April 30, 200817 yr is it possible to prepend files add text or lines at the beginning of the file vs only append?
May 1, 200817 yr I'm not aware of a one-liner for doing this. I'd recommend creating a temporary file, writing your text to it, then copying the existing file to the end of the tmp file. Then close the tmp file and move it over the old file, replacing it. File f = new File(path) if (!f.exists()) throw new FileNotFoundException(path + " does not exist") File tmp = File.createTempFile("prepending", ".txt") tmp.write(text + "n") tmp.append(f.getText()) tmp.renameTo(f)
May 1, 200817 yr I haven't tried this, but I think this will do what you want: RandomAccessFile raf = new RandomAccessFile( new File("TheFile.txt"), "rw"); raf.seek( 0 ); /*This is the position in the file that you want to write */ raf.writeChars("Hey there"); raf.close(); Edited May 1, 200817 yr by Guest
May 8, 200817 yr I think that overwrites instead of appending. It also seems to write it in an odd encoding.
Create an account or sign in to comment