Jump to content
Claris Engage 2025 - March 25-26 Austin Texas ×

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

Recommended Posts

Posted

is it possible to prepend files add text or lines at the beginning of the file vs only append?

Posted

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)

Posted (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 by Guest
Posted

I think that overwrites instead of appending. It also seems to write it in an odd encoding.

This topic is 6053 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.