Suppose I have a file named abhishek.txt and that contains the following line
I am , and what is your name.
Now I want to write
Abhishek
after "I am" like I am Abhishek, .. How to write the content in this specific position directly.
You can't insert data into a file... file systems (in general) simply don't support such an operation. Typically you'd open one file for reading and another for writing, copy the first part of the file from one stream to the other, write the extra part, then copy the second part of the file.
If you're trying to replace the original file, you'd then need to delete it and move the new file into place.
Sometimes it may be simpler to read the whole file into memory in one go - it depends on exactly what you're trying to do, and how big the file is.
You can't insert data into a file. You can overwrite data at a specific location with RandomAccessFile
. However an insert requires changing all of the data after it. For your case try something like this instead:
File file = new File("abhishek.txt");
Scanner scanner = new Scanner(file).useDelimiter("\n");
String line = scanner.next();
String newLine = line.substring(0, 5) + "Abhishek" + line.substring(5);
FileWriter writer = new FileWriter(file);
writer.write(newLine);
writer.close();
Generally speaking you need to read the old file, modify the contents in memory and write it back out again.
There are many options here, as to whether you read the file all at once, or a small piece at a time, whether you replace the existing file, etc, but this is generally the pattern to use.
I managed to do it using RandomAccessFile:
With this, you get a file containing exactly the expected 'I am Abhishek' content. This works even if you would had content after the first line, which you want to keep in the file(this was my initial problem: I had a large file and I had to insert some content after a certain String) rather than write at the end of the file, which is easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With