Ocean West Posted April 30, 2008 Share Posted April 30, 2008 is it possible to prepend files add text or lines at the beginning of the file vs only append? Link to comment Share on other sites More sharing options...
shmert Posted May 1, 2008 Share Posted May 1, 2008 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) Link to comment Share on other sites More sharing options...
Jesse Barnum Posted May 1, 2008 Share Posted May 1, 2008 (edited) 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, 2008 by Guest Link to comment Share on other sites More sharing options...
shmert Posted May 8, 2008 Share Posted May 8, 2008 I think that overwrites instead of appending. It also seems to write it in an odd encoding. Link to comment Share on other sites More sharing options...
Recommended Posts
This topic is 5839 days old. Please don't post here. Open a new topic instead.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now