Jump to content
Server Maintenance This Week. ×

Prepend to files


This topic is 5839 days old. Please don't post here. Open a new topic instead.

Recommended Posts

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

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 by Guest
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.