I want to write a string into the beginning of a file, How do I do that?
I don’t know how to add a string at all.. This is what I did so far:
public static void prepend (String filename, String data) throws IOException{
FileOutputStream file= new FileOutputStream(filename);
}
(i) The write() method accepts only bytes- What should I do in order to use it in my case?
(ii)-How do I copy the string to the beginning of the file?
And- If someone knows about a web-site that has all the Writers\Readers and all these streams arranged and well explained- I will really appreciate it, I’m losing my mind.
Thanks!
To write text, you need to create a
Writer– such asOutputStreamWriter. You can useFileWriterinstead, but I prefer to wrap aFileOutputStreamin anOutputStreamWriteras that way I can control the encoding.You can’t really prepend to the start of a file though – you’ll have to write the new text to the start of a new file, then copy the contents of the old file afterwards, then rename the files if necessary. Exactly how you do that will depend on the contents of the existing file.